Reputation: 4359
I have an array that may look like
$arr = array(
array(
'test1' => 'testing1'
),
array(
'test2' => array(
1 =>'testing2
)
);
and I want to turn it into
$newArr = array(
'test1' => 'testing1',
'test2' => array(
1 => 'testing2'
)
);
so i have been trying to shift all array elements up one level.
eidt:
this is my method that combines 2 array together:
public function arrayMerge($arr1, $arr2)
{
foreach($arr2 as $key => $value) {
$condition = (array_key_exists($key, $arr1) && is_array($value));
$arr1[$key] = ($condition ? $this->arrayMerge($arr1[$key], $arr2[$key]) : $value);
}
return $arr1;
}
Upvotes: 16
Views: 23420
Reputation: 95121
Try
$arr = array(
array('test1' => 'testing1' ),
array('test2' => array(1 =>'testing2'))
);
$new = array();
foreach($arr as $value) {
$new += $value;
}
var_dump($new);
Output
array
'test1' => string 'testing1' (length=8)
'test2' =>
array
1 => string 'testing2' (length=8)
Upvotes: 14
Reputation: 197832
It's somewhat trivial, many ways are possible.
For example using the array union operator (+
)Docs creating the union of all arrays inside the array:
$newArr = array();
foreach ($arr as $subarray)
$newArr += $subarray;
Or by using array_merge
Docs with all subarrays at once via call_user_func_array
Docs:
$newArray = call_user_func_array('array_merge', $arr);
Upvotes: 28