php数组里面嵌套数
While browsing the MooTools 1.2 source code, I found Array's flatten()
method. The flatten()
method takes nested arrays and "flattens" them all into one array. I asked myself how I could do that using PHP. The following is what I came up with.
浏览MooTools 1.2源代码时,我发现了Array的flatten()
方法。 flatten()
方法采用嵌套数组,并将它们全部“展平”为一个数组。 我问自己如何使用PHP做到这一点。 以下是我想到的。
PHP (The PHP)
$myarray = array('a', 'b', array(array(array('x'), 'y', 'z')), array(array('p')));
function array_flatten($array,$return) {
for($x = 0; $x <= count($array); $x++) {
if(is_array($array[$x])) {
$return = array_flatten($array[$x], $return);
}
else {
if(isset($array[$x])) {
$return[] = $array[$x];
}
}
}
return $return;
}
$res = array_flatten($myarray, array());
结果 (The Result)
Array
(
[0] => a
[1] => b
[2] => x
[3] => y
[4] => z
[5] => p
)
As you can see, array_flatten()
is used recursively to sniff out values from the original array. While I don't believe I've ever found myself with an array as nested as my example, it's good to know that I can extract the values if necessary.
如您所见, array_flatten()
递归用于从原始数组中嗅出值。 虽然我不相信自己曾经像示例中那样嵌套过数组,但很高兴知道我可以在必要时提取值。
php数组里面嵌套数