开发者

array_walk_recursive PHP4

开发者 https://www.devze.com 2023-02-18 08:51 出处:网络
How can I emulate the following behavior in PHP4 within a Class. $sample = array(\'dog\' => \'woof\', \'cat\' => array(\'angry\' => \'hiss\', \'happy\' => \'purr\'), \'aardvark\' => \'

How can I emulate the following behavior in PHP4 within a Class.

$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);

print_r($output);

/* 
开发者_C百科* Array
* (
*  [0] => woof
*  [1] => hiss
*  [2] => purr
*  [3] => kssksskss
* )

*/


Here's a straightforward implementation:

function array_walk_recursive(&$input, $callback, $userdata = null) {
    foreach($input as $key => &$value) {
        if (is_array($value)) {
            if(!array_walk_recursive($value, $callback, $userdata)) {
                return false;
            }
        }
        else {
            call_user_func($callback, $value, $key, $userdata);
        }
    }

    return true;
}

The one thing this will not do is return false. I didn't see in the docs for array_walk when that might happen, so I left it out.

0

精彩评论

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