Restructure multidimensional array of column data into multidimensional array of row data [duplicate]
As Kris Roofe stated in his deleted answer, array_column
is indeed a more elegant way. Just be sure to put it into some kind of a foreach
loop, similar to what Sahil Gulati showed you. For example, like this:
$result = array();
foreach($where['id'] as $k => $v)
{
$result[] = array_column($where, $k);
}
The var_dump
output of $result
is exactly what you're looking for
array(3) {
[0]=>
array(2) {
[0]=>
int(12)
[1]=>
string(10) "1999-06-12"
}
[1]=>
array(2) {
[0]=>
int(13)
[1]=>
string(10) "2000-03-21"
}
[2]=>
array(2) {
[0]=>
int(14)
[1]=>
string(10) "2006-09-31"
}
}
Solution 1: Hope this simple foreach
to get the desired result
Try this code snippet here
<?php
ini_set('display_errors', 1);
$where = array('id'=>array(12,13,14),'date'=>array('1999-06-12','2000-03-21','2006-09-31'));
$result=array();
foreach($where["id"] as $key => $value)
{
$result[]=array($value,$where["date"][$key]);
}
Solution 2: Here we are using array_walk
to achieve the same result
Try this code snippet here
<?php
ini_set('display_errors', 1);
$result=array();
$where = array('id'=>array(12,13,14),'date'=>array('1999-06-12','2000-03-21','2006-09-31'));
array_walk($where["id"], function($value,$key) use(&$result,&$where){
$result[]=array($value,$where["date"][$key]);
});
print_r($result);
Solution 3: Here we are using array_shift
on $where["date"]
.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$result=array();
$where = array('id'=>array(12,13,14),'date'=>array('1999-06-12','2000-03-21','2006-09-31'));
foreach($where["id"] as $value)
{
$result[]=array($value, array_shift($where["date"]));
}
print_r($result);
I've completely re-written my answer because it was unnecessarily bloating this page. Truth is, there is a very clean and native way to handle this specific task of "transposing". Using null
as the function argument and passing in the two known rows from the input array is all that is required.
Code: (Demo)
$where = [
'id' => [12, 13, 14],
'date' => ['1999-06-12', '2000-03-21', '2006-09-31']
];
var_export(
array_map(null, $where['id'], $where['date'])
);
Output:
array (
0 =>
array (
0 => 12,
1 => '1999-06-12',
),
1 =>
array (
0 => 13,
1 => '2000-03-21',
),
2 =>
array (
0 => 14,
1 => '2006-09-31',
),
)
For anyone that truly needs a dynamic solution (because the number of rows may fluxuate/change and you don't want to keep maintaining the processing code), then I recommend that you check the version history of my answer.