Search code examples
phparraysrecursionmultidimensional-arraytraversal

Recursively generate a flat, indexed array of all values/leafnodes from a multidimensional array of unknown depth


N in this question means any arbitrary number of any size and is not necessarily (but could be) the same. I have an array with N number of key => value pairs. These key => value pairs can also contain another array of size N with N number of key => value pairs. This array can be of N depth, meaning any key => value pair in the array could map to another array.

How do I get all the values of this array (storing them in a new, 1 dimensional array), ignoring the keys in the key => value pairs?


Solution

  • array-walk-recursive

    rob at yurkowski dot net 26-Oct-2010 06:16

    If you don't really particularly care about the keys of an array, you can capture all values quite simply:

    $sample = array(
        'dog' => 'woof',
        'cat' => array(
            'angry' => 'hiss',
            'happy' => 'purr'
        ),
        'aardvark' => 'kssksskss'
    );
    
    $output = array();
    
    // Push all $val onto $output. 
    array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &$output);
    // Printing echo nl2br(print_r($output, true));
    
    /*
     * Array
     * (
     *  [0] => woof
     *  [1] => hiss
     *  [2] => purr
     *  [3] => kssksskss
     * )
     */