merge all values of keys in array php

193 views Asked by At

Don't know this question is asked before or not, cannot find after lot of searching.

My array looks like this,

array(3) {
  [0]=>
  array(2) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
    [1]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
  }
  [1]=>
  array(1) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
  }
  [4]=>
  array(2) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [1]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
  }
}

What I want is,

array(1) {
  [0]=>
  array(5) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
    [1]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [2]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [3]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [4]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
  }
}

I have tried with array_merge, array_combine and a lot of foreach() loops. But didn't get luck for desired output.

Don't know how to do this. Please help.

1

There are 1 answers

3
Saumya Rastogi On BEST ANSWER

You can flatten your array like this:

$arr = array(array(['user' => 1], ['user' => 2]), ['user' => 3]);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($iterator as $val) {
  $flattened_arr[0][] = $val;
}
var_dump($flattened_arr);

UPDATE: If you don't want to use RecursiveIteratorIterator, the you can also do it like this using array_walk_recursive():

$non_flat_arr = array(array(['user' => 1], ['user' => 2]), ['user' => 3]);
$objTmp = (object) array('flat_arr' => array());
array_walk_recursive($non_flat_arr, create_function('&$v, $k, &$t', '$t->flat_arr[] = $v;'), $objTmp);
var_dump([ 0 => $objTmp->flat_arr]);

This will give you the output as:

array:1 [
  0 => array:3 [
    0 => 1
    1 => 2
    2 => 3
  ]
]

Hope this helps!