Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify an array with PHP

Tags:

arrays

php

Seems like a pretty basic question, but how can I simplify an array such as:

Array
(
    [0] => Array
        (
            [blue_dog_1] => 2
        )
    [1] => Array
        (
            [red_dog_1] => 4
        )
    [2] => Array
        (
            [red_dog_2] => 6
        )
)

To be like:

Array
(
    [blue_dog_1] => 2
    [red_dog_1] => 4
    [red_dog_2] => 6
)

Thanks in advance.

like image 233
Matthew Woodard Avatar asked Dec 02 '25 13:12

Matthew Woodard


2 Answers

Try this way to make it single dimension from multi dimension using array_merge

$singleD = array_reduce($multiD, 'array_merge', array());

OR

$singleD = call_user_func_array('array_merge', $multiD);
like image 173
Always Sunny Avatar answered Dec 05 '25 03:12

Always Sunny


Try this,

foreach($array as $sub_val)
{
   foreach($sub_val as $key=>$val)
   {
      $new_array[$key] = $val;
   }
}
print_r($new_array);
like image 29
Dave Avatar answered Dec 05 '25 02:12

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!