I want to combine these arrays in a new array based on the same key number for creating tables. This is my code.
$arr3 = array();
print '<pre>';
print_r($bonus_table);
print '</pre>';
foreach($bonus_table as $key => $row) {
$arr3 = array_merge($row['cells'],$arr3);
}
return $arr3;
And this is the output from my code. Basically this is the current structure of array:
Array
(
[0] => Array
(
[cells] => Array
(
[0] => DEPOTS
[1] => PRICES
)
)
[1] => Array
(
[cells] => Array
(
[0] => 50
[1] => 25
)
)
[2] => Array
(
[cells] => Array
(
[0] => 100
[1] => 50
)
)
)
But I want to convert the above output with the below structure. The desired array should look like this:
Array
(
[0] => Array
(
[cells] => Array
(
[0] => DEPOTS
[1] => 50
[2] => 100
)
)
[1] => Array
(
[cells] => Array
(
[0] => PRICES
[1] => 25
[2] => 50
)
)
)
3
Answers
Replacing your
foreach
loop with the below will produce the data you are after:Demo: https://onlinephp.io/c/06b36
Here we are looping through the input array (
$bonus_table
) and collecting data in an output array ($arr3
).You simply could use
array_column
outout
Because you have 3 levels in your array and the middle level uses
cells
as the key which needs to be retained, array transposition can be done swiftly without out any function calls by nesting a loop inside of another.For the record, I don’t see a lot of value in having the redundant
cells
level in your array structure.Code: (Demo)