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>
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>
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>
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!