Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shift all array elements up one level in a multidimensional array

Tags:

php

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;
            }
like image 644
Eli Avatar asked May 03 '12 23:05

Eli


People also ask

What does array_ shift do in PHP?

The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).

How do you shift a 2d array to the right in Java?

To shift the bits of array elements of a 2d array to the right, use the numpy. right_shift() method in Python Numpy. Bits are shifted to the right x2.

How to pop first element of array in PHP?

Answer: Use the PHP array_shift() function You can use the PHP array_shift() function to remove the first element or value from an array. The array_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL .


2 Answers

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);
like image 94
hakre Avatar answered Oct 17 '22 03:10

hakre


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)
like image 21
Baba Avatar answered Oct 17 '22 03:10

Baba