Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : flatten array - fastest way?

Tags:

arrays

php

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
        )
)
like image 680
Industrial Avatar asked May 28 '10 16:05

Industrial


1 Answers

Give this a shot:

$ret = array();
while ($el = each($array)) {
    $ret[$el['value']['key']] = $el['value']['value'];
}
like image 180
ircmaxell Avatar answered Sep 25 '22 02:09

ircmaxell