Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values from multidimensional array

Tags:

arrays

php

Let's say, I have an array like this:

$array = [
    'car' => [
        'BMW' => 'blue',
        'toyota' => 'gray'
        ],
    'animal' => [
        'cat' => 'orange',
        'horse' => 'white'
        ]
    ];

Then, I want to get all the values (the colour, 'blue', 'gray', 'orange', 'white') and join them into a single array. How do I do that without using foreach twice?

Thanks in advance.

like image 645
Vaivez66 Avatar asked Dec 18 '22 15:12

Vaivez66


2 Answers

TL;DR

$result = call_user_func_array('array_merge', $array);

Credit: How to "flatten" a multi-dimensional array to simple one in PHP?

In your use case, you should use it like this:

<?php
$array = [
    'car' => [
        'BMW' => 'blue',
        'toyota' => 'gray'
        ],
    'animal' => [
        'cat' => 'orange',
        'horse' => 'white'
        ]
    ];
$result = call_user_func_array('array_merge', $array);
$result = array_values($result);

//$result = ['blue', 'gray', 'orange', 'white']
like image 156
Ng Sek Long Avatar answered Dec 30 '22 03:12

Ng Sek Long


Old but as far i see not really a "working on all cases" function posted.

So here is the common classic recursively function:

function getArrayValuesRecursively(array $array)
{
    $values = [];
    foreach ($array as $value) {
        if (is_array($value)) {
            $values = array_merge($values,
                getArrayValuesRecursively($value));
        } else {
            $values[] = $value;
        }
    }
    return $values;
}

Example array:

$array = [
    'car'    => [
        'BMW'    => 'blue',
        'toyota' => 'gray'
    ],
    'animal' => [
        'cat'   => 'orange',
        'horse' => 'white'
    ],
    'foo'    => [
        'bar',
        'baz' => [
            1,
            2 => [
                2.1,
                'deep' => [
                    'red'
                ],
                2.2,
            ],
            3,
        ]
    ],
];

Call:

echo var_export(getArrayValuesRecursively($array), true) . PHP_EOL;

Result:

// array(
//     0 => 'blue',
//     1 => 'gray',
//     2 => 'orange',
//     3 => 'white',
//     4 => 'bar',
//     5 => 1,
//     6 => 2.1,
//     7 => 'red',
//     8 => 2.2,
//     9 => 3,
// )
like image 37
cottton Avatar answered Dec 30 '22 04:12

cottton