Move all elements of an array one level in a multidimensional array

I have an array that might 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'm trying to move all elements of the array one level.

Eidt:

this is my method that concatenates 2 arrays 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; } 
+8
php
source share
2 answers

Try

 $arr = array( array('test1' => 'testing1' ), array('test2' => array(1 =>'testing2')) ); $new = array(); foreach($arr as $value) { $new += $value; } var_dump($new); 

Exit

 array 'test1' => string 'testing1' (length=8) 'test2' => array 1 => string 'testing2' (length=8) 
+10
source share

This is somewhat trivial, perhaps in many ways.

For example, using the array join operator ( + ) & shy; Docs creating a union of all arrays inside the array:

 $newArr = array(); foreach ($arr as $subarray) $newArr += $subarray; 

Or using array_merge & shy; Docs with all subarrays immediately through call_user_func_array & shy; Docs :

 $newArray = call_user_func_array('array_merge', $arr); 
+16
source share

All Articles