PHP: is flatten array the fastest way?

Is there any quick way to smooth the array and select the subkeys ('key' & 'value' in this case) without starting the foreach loop, or is it always the fastest foreach way?

Array
(
    [0] => Array
        (
            [key] => string
            [value] => a simple string
            [cas] => 0
        )

    [1] => Array
        (
            [key] => int
            [value] => 99
            [cas] => 0
        )

    [2] => Array
        (
            [key] => array
            [value] => Array
                (
                    [0] => 11
                    [1] => 12
                )

            [cas] => 0
        )

)

To:

Array
(
    [int] => 99
    [string] => a simple string
    [array] => Array
        (
            [0] => 11
            [1] => 12
        )
)
+5
source share
3 answers

Take a picture:

$ret = array();
while ($el = each($array)) {
    $ret[$el['value']['key']] = $el['value']['value'];
}
+3
source

call_user_func_array("array_merge", $subarrays)can be used to "smooth" nested arrays.
What you want is completely different. You can use array_walk()with a callback to extract the data in the desired format. But no, the foreach loop is even faster. There is no way array_*to achieve your structure otherwise.

+3
source

. , . , ; .

function array_flatten(/* ... */)
{
    $flat = array();
    array_walk_recursive(func_get_args(), function($value, $key)
    {
        if (array_key_exists($key, $flat))
        {
            if (is_int($key))
            {
                $flat[] = $value;
            }
        }
        else
        {
            $flat[$key] = $value;
        }
    });
    return $flat;
}

Instead of !isset($key)or empty($key)you can use useful values.

Here's a shorter option:

function array_flatten(/* ... */)
{
    $flat = array();
    array_walk_recursive(func_get_args(), function($value, $key) use (&$flat)
    {
        $flat = array_merge($flat, array($key => $value));
    });
    return $flat;
}
-1
source

All Articles