开发者

Traversing all values of an array of arrays

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 开发者_如何学Python(storing them in a new, 1 dimensional array), ignoring the keys in the key => value pairs?


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
 * )
 */


You could do smt like this:

$output = array();

function genArray( $arr ) {
    global $output;
    foreach( $arr as $key => $val ) {
        if( is_array($val) ) 
            genArray( $val );
        else
            output[$key] = $val;
    }
}

genArray( $myArray );

Instead of recursion, using global variable and function, it could be done via loops, but this is just a general idea, and probably needs a little of your attention, anyway. That should be a good thing :)


There are a ton of solutions in the comments of the array_values php doc.

http://www.php.net/manual/en/function.array-values.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜