hasChildren() 的工作方式如本文档所述,但与其名称暗示的不符。
此方法不会返回当前条目是否真正 *拥有* 子项。它只返回元素的类型是否能够拥有子项。
如果您正在处理空数组,这有点违反直觉。
示例
<?php
$data = array(
"element one" => array(true),
"element two" => array(),
"element three" => array(true),
);
$i = new RecursiveIteratorIterator(new RecursiveArrayIterator($data),RecursiveIteratorIterator::SELF_FIRST);
foreach($i as $key => $value)
{
$type = gettype($value);
$depth = $i->getDepth();
if($i->hasChildren()) {
echo "$depth: $key ($type) has children\n";
} else {
echo "$depth: $key ($type) has no children\n";
}
}
?>
结果
0: element one (array) has children
1: 0 (boolean) has no children
0: element two (array) has children
0: element three (array) has children
1: 0 (boolean) has no children