How to Transform a Multidimensional Array from Columnar to Rowar Structure?

Susan Sarandon
Release: 2024-10-26 15:11:30
Original
337 people have browsed it

How to Transform a Multidimensional Array from Columnar to Rowar Structure?

Transforming Columnar Data Structure to a Rowar Structure in Multidimensional Arrays

In programming, it may be necessary to convert a multidimensional array with columns of data into one with rows of merged data. This transformation can be achieved by rotating the array structure.

Consider the following associative array representing column data:

<code class="php">$where = array(
    'id' => array(
        12,
        13,
        14
    ),
    'date' => array(
        '1999-06-12',
        '2000-03-21',
        '2006-09-31'
    )
);</code>
Copy after login

The desired output is a multidimensional array with rows of merged data, as seen below:

<code class="php">$comb = array(
    array(12, '1999-06-12'),
    array(13, '2000-03-21'),
    array(14, '2006-09-31')
);</code>
Copy after login

This transformation can be achieved using a combination of the array_column and looping techniques. The array_column function extracts a specified column from an array, while a loop iterates through each column to create the desired row format.

Here's a code snippet to accomplish this:

<code class="php">$result = array();

foreach($where['id'] as $k => $v)
{
  $result[] = array_column($where, $k);
}</code>
Copy after login

This code iterates through the id column and uses array_column to extract the corresponding values from the date column. The resulting array $result contains rows of merged data, meeting the requirements of the expected output.

The above is the detailed content of How to Transform a Multidimensional Array from Columnar to Rowar Structure?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!