如何从多维数组中删除所有叶子?
这段代码给了我所有的叶子,我正在寻找相反的结果:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
$result[] = array($key, $value);
}
是否有内置的?或者任何其他优雅的解决方案?
ParentIterator可以帮助您。
<?php
$array = [
'a',
'b'=>[
'c'=>[],
'd'
],
'e',
'f'=>[
'g'=>[
'h',
'i'=>[
'j'=>[],
'k'
]
]
]
];
$rii = new RecursiveIteratorIterator(
new ParentIterator(
new RecursiveArrayIterator($array)
),
RecursiveIteratorIterator::CHILD_FIRST
);
$result = [];
foreach($rii as $key => $dummy) {
echo $key, "rn";
}
打印
c
b
j
i
g
f