假设我在PHP中有一个看起来像这样的数组
array
(
array(0)
(
array(0)
(
.
.
.
)
.
.
array(10)
(
..
)
)
.
.
.
array(n)
(
array(0)
(
)
)
)
Run Code Online (Sandbox Code Playgroud)
而且我需要将这个多维数组的所有叶子元素都变成一个线性数组,我应该如何在不借助递归的情况下这样做呢?
function getChild($element)
{
foreach($element as $e)
{
if (is_array($e)
{
getChild($e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:上面的代码片段,可怕的未完成
更新:数组的示例
Array
(
[0] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 5000000
[balance:private] => 4998970
[queueid:private] => 0
[sellerid:private] => 2
[dateTime:private] => 2009-07-25 17:53:10
)
)
)
Run Code Online (Sandbox Code Playgroud)
...剪断.
[2] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 10000000
[balance:private] => 9997940
[queueid:private] => 135
[sellerid:private] => 234
[dateTime:private] => 2009-07-14 23:36:00
)
)
....snipped....
)
Run Code Online (Sandbox Code Playgroud)
)
J.C*_*cio 11
实际上,有一个功能可以解决问题,请查看手册页:http://php.net/manual/en/function.array-walk-recursive.php
从页面改编的快速片段:
$data = array('test' => array('deeper' => array('last' => 'foo'), 'bar'), 'baz');
var_dump($data);
function printValue($value, $key, $userData)
{
//echo "$value\n";
$userData[] = $value;
}
$result = new ArrayObject();
array_walk_recursive($data, 'printValue', $result);
var_dump($result);
Run Code Online (Sandbox Code Playgroud)
您可以使用迭代器,例如:
$result = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::LEAVES_ONLY) as $value) {
$result[] = $value;
}
Run Code Online (Sandbox Code Playgroud)