nishant nishant - 4 years ago 84
PHP Question

Remove the top level array and merge sub array into one

I have a multidimensional array and I want to remove the top level array and merge all its sub array into one array.
Below is my array:

$arr = [KEY1] => Array
(
[0] => Array
(
[Feb] => 120
)

[1] => Array
(
[Jan] => 230
)
[3] => Array
(
[Mar] => 340
)

)

[KEY2] => Array
(
[0] => Array
(
[Feb] => 12
)

[1] => Array
(
[Jan] => 23
)
[3] => Array
(
[Mar] => 34
)
)


I need to arrange and sort this array like below:

Output:

[KEY1] => Array
(
[Jan] => 230,
[Feb] => 120,
[Mar] => 340
)
[KEY2] => Array
(
[Jan] => 23,
[Feb] => 12,
[Mar] => 34
)


I have used

call_user_func_array('array_merge', $arr ); but not working.

Please suggest any wise way to do this.

Thanks

Answer Source

You can try like this as simple way,

     $arr = [
      'key1' =>[
          0 => ["feb" => 123],
          1 => ["dev" => 213],
          2 => ["jan" => 111],
      ],
      'key2' =>[
          0 => ["feb" => 132],
          1 => ["dev" => 321],
          2 => ["jan" => 555],
      ],
      ];
      $result = [];
      foreach($arr as $k => $v){
          foreach($v as $k1 => $v1){
              foreach($v1 as $k2 => $v2)
              $result[$k][$k2] = $v2;
          }
      }
      print_r($result);

Hope this will solve your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download