Reputation: 189
How can I flatten an array while retaining its keys?
Say for example I have the following array:
array (size=2)
0 =>
array (size=1)
'bonus' => float 20
1 =>
array (size=1)
'bonus_percent' => float 2
array (size=1)
'bonus_all' => float 22
How can I "flatten" it to be like this? :
array (size=2)
'bonus' => float 20
'bonus_percent' => float 2
'bonus_all' => float 22
I have found this function from SO also, which results to the current results.
$objTmp = (object) array('aFlat' => array());
array_walk_recursive($results, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
var_dump($results);
Upvotes: 0
Views: 58
Reputation: 91734
If there are no deeper levels you need to flatten, a loop is probably an easier solution than using array_walk_recursive()
.
Something like:
$original = array(...);
$result = array();
foreach ($original as $value) {
$result += $value;
}
Upvotes: 2