tags:

views:

62

answers:

2

Is there any fast way to flatten an array and select subkeys ('key'&'value' in this case) without running a foreach loop, or is the foreach always the fastest 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
        )
)
A: 

Give this a shot:

$ret = array();
while ($el = each($array)) {
    $ret[$el['value']['key']] = $el['value']['value'];
}
ircmaxell
oh what an ancient operators :)
Col. Shrapnel
+1  A: 

call_user_func_array("array_merge", $subarrays) can be used to "flatten" nested arrays.
What you want is something entirely different. You could use array_walk() with a callback instead to extract the data into the desired format. But no, the foreach loop is still faster. There's no array_* method to achieve your structure otherwise.

mario
array_walk wouldn't work in itself, because it doesn't return anything except a bool (and you can't modify the key of the array).
ircmaxell