Home > Software engineering >  PHP - How to combine a list of arrays that are at the same level
PHP - How to combine a list of arrays that are at the same level

Time:08-20

After flattening a multidimensional array, I have a resulting array, which running print_r() on gives me the following output:

Array
(
    [0] => 9999
)
Array
(
    [0] => 8888
)
Array
(
    [0] => 7777
)
Array
(
    [0] => 6666
)

I'm hoping to combine these arrays, so that print_r() would output it like this:

Array
(
    [0] => 9999
    [1] => 8888
    [2] => 7777
    [3] => 6666
)

Looking through stackoverflow and other documentation, I've seen suggestions on array_merge, array_merge_recursive, array_combine, implode, and others, but for some reason (maybe because these arrays are all at the same level?), these suggestions haven't worked.

Thanks in advance for any ideas.

Here is a simplified example of how I'm getting this strange output:

$multi_dim_array = array(
        array("Details"=>array("Category"=>array("CategoryId" => 15, "CategoryName" => "Misc Products"), "Id" => 1, "Number" => 9999)),
        array("Details"=>array("Category"=>array("CategoryId" => 12, "CategoryName" => "Random Products"), "Id" => 2, "Number" => 8888))
    );


    function array_flatten($array) {

        $return = array();
        $nums = array();

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $return = array_merge($return, array_flatten($value));
            } else {
                $return[$key] = $value;
            }       
            
        }
        
        if(isset($return["Number"])) {      
        
            array_push($nums, $return["Number"]);
    
            // echo "<pre>";
            //   // var_dump($array);
            //   print_r($nums);
            // echo "</pre>";

            $output = array_reduce($nums, function($carry, $item) {
                $carry[] = $item;
                return $carry;
               }, []);
              
            echo "<pre>";   
                print_r($output);
            echo "</pre>";
        }   

        return $return;
    }

    $result = array_flatten($multi_dim_array);

CodePudding user response:

Initial Variable

$arr = [
 [ 999999 ],
 [ 888888 ],
 [ 777777 ],
 [ 666666 ]
];

One liner:

$output = array_merge(...$arr);
print_r($output);

With reduce

// This is your format
$output = array_reduce($arr, function($carry, $item) {
 $carry[] = $item;
 return $carry;
}, []);

print_r($output);

Output

Array
(
    [0] => 999999
    [1] => 888888
    [2] => 777777
    [3] => 666666
)

CodePudding user response:

Try this:

$new_array = array_merge(...$old_array);
print_r($new_array);

Also see: https://www.php.net/manual/en/function.array-merge.php

  • Related