Arsalan Arsalan - 1 month ago 14
PHP Question

Need assistance with Php Arrays merge

I'm working on a project, where I get an Array like this

Array
(
[0] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
[1] => Array
(
[0] => value4
[1] => value5
[2] => value6
)
[2] => Array
(
[0] => value7
[1] => value8
[2] => value9
)
)


I want to merge it like this

Array
(
[0] => value1
[1] => value2
[2] => value3
[3] => value4
[4] => value5
[5] => value6
[6] => value7
[7] => value8
[8] => value9
)


Im using php 5.6, any help would be greatly appreciated!

Answer

You can try this function:

function array_flatten($array)
{
    if (!is_array($array)) {
        return false;
    }

    $result = [];
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $result = array_merge($result, array_flatten($value));
        } else {
            $result[$key] = $value;
        }
    }

    return $result;
}
Comments