Share Knowledge Share Knowledge - 4 months ago 15
PHP Question

PHP - Copy a multidimensional array by grouping its keys based on the values index

I have multidimensional array which looks like this. This is my snippet down below:

$tyreSpec = array(
'width_id' => array(
0 => '8',
1 => '24'
),
'profile_id' => array(
0 => '8',
1 => '13'
),
'diameter_id' => array(
0 => '4',
1 => '13'
),
'speed_id' => array(
0 => '6',
1 => '13'
),
'load_id' => array(
0 => '12',
1 => '31'
)
);


How can I create an array like this from the above one?

$toDb = array (
array(
'width_id' => 8,
'profile_id' => 8,
'diameter_id' => 4,
'speed_id' => 6,
'load_id' => 12
),
array(
'width_id' => 24,
'profile_id' => 13,
'diameter_id' => 13,
'speed_id' => 13,
'load_id' => 31
)
);


This is my code down below I can't get it done:

$ToDb = array();
//$i = 0;
$count = 0;
foreach($tyreSpec as $row ) {
$count = count($row);
}

for($i = 0; $i < $count; $i++) {
foreach($tyreSpec as $row) {
array_push($ToDb, $row[$i]);
}
}

Answer

You can use two simple loops to achieve your goal:

$toDb = array();
foreach ($tyreSpec as $key=>$val) {
    for ($i=0; $i<count($val); ++$i)
        $toDb[$i][$key] = $val[$i];
}
Comments