我有一个recursivearray,它不返回特定数组结构中的对象/元素:
尝试使用递归的数组如下:
$feedStruct = [database] => Array
(
[property] => Array
(
[0] => Array
(
[title] => Array
(
)
[tipology] => Array
(
)
[description] => Array
(
)
[location] => Array
(
)
[year] => Array
(
)
[price] => Array
(
)
[area_plot] => Array
(
)
[habitable_area] => Array
(
)
[ref] => Array
(
)
[video] => Array
(
)
[default_photo] => Array
(
)
[photo1] => Array
(
)
)
[1] => Array
(
[title] => Array
(
)
[tipology] => Array
(
)
[description] => Array
(
)
[location] => Array
(
)
[year] => Array
(
)
[price] => Array
(
)
[area_plot] => Array
(
)
[habitable_area] => Array
(
)
[ref] => Array
(
)
[video] => Array
(
)
[default_photo] => Array
(
)
[photo1] => Array
(
)
)
)
)
代码如下:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($feedStruct));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$val = $iterator->getSubIterator($i)->key();
}
}
当使用上面的数组运行它不会迭代,其他数组我没有问题,任何想法为什么?
谢谢
答案 0 :(得分:0)
您的$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($feedStruct));
将被解释为$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($feedStruct), RecursiveIteratorIterator::SELF_FIRST);
,因为RecursiveIteratorIterator::LEAVES_ONLY
是三个中的默认参数(即RecursiveIteratorIterator::SELF_FIRST
,RecursiveIteratorIterator::CHILD_FIRST
)。
我会尝试解释参数。假设你有下面的数组
$array = array(
0 => array(
'city' => 'Jos',
'places_to_visit' => array(
'Lagos',
'Capetown'
)
),
1 => "sd"
);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($feedStruct), $mode);
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$val[] = $iterator->getSubIterator($i)->key();
}
}
RecursiveIteratorIterator::LEAVES_ONLY
表示仅迭代每个结构中的最后一个值。如果是上面的数组$array
,请$mode = RecursiveIteratorIterator::LEAVES_ONLY
,
print_r($val);
/* Outputs
city => Jos
0 => Lagos
1 => Capetown
1 => sd */
RecursiveIteratorIterator::CHILD_FIRST
表示在父母之前首先迭代子值。如果是上面的数组$array
,请$mode = RecursiveIteratorIterator::CHILD_FIRST
,
print_r($val);
/* Outputs
city => Jos
0 => Lagos
1 => Capetown
places_to_visit => Array()
0 => Array()
1 => sd */
RecursiveIteratorIterator::SELF_FIRST
表示在每个结构中首先仅迭代父值。如果是上面的数组$array
,请$mode = RecursiveIteratorIterator::SELF_FIRST
,
print_r($val);
/*Outputs
0 => Array()
city => Jos
places_to_visit => Array()
0 => Lagos
1 => Capetown
1 => sd */
在您的情况下,$iterator
将返回 0 ,因为您的结构$feedStruct
中没有叶子(最终值)。试试RecursiveIteratorIterator::SELF_FIRST
,效果很好。