下面是我拥有的数组的结构。我有两个问题:
例如,如何在[post_id] => 2782
内获取元素[2772] => Array
的数组位置(答案应为4)?
例如,如何获得元素为[post_id] => 2779
的数组的子数组(答案应为2)?
Array
(
[2772] => Array
(
[post_id] => 2772
[children] => Array
(
[0] => Array
(
[post_id] => 2774
[children] => Array
(
[0] => Array
(
[post_id] => 2779
[children] => Array
(
[0] => Array
(
[post_id] => 2782
[children] => Array
(
)
)
[1] => Array
(
[post_id] => 2781
[children] => Array
(
)
)
)
)
[1] => Array
(
[post_id] => 2780
[children] => Array
(
[0] => Array
(
[post_id] => 2784
[children] => Array
(
)
)
)
)
)
)
[1] => Array
(
[post_id] => 2775
[children] => Array
(
)
)
[2] => Array
(
[post_id] => 2776
[children] => Array
(
)
)
)
)
)
答案 0 :(得分:0)
您可以使用此功能计算所有孩子:
function GetChildrenQuantity($element){
$quantity = count($element->children);
$childrenQuantity = 0;
for($i=0;$i<$quantity;$i++){
$childrenQuantity += GetChildrenQuantity($element->children[i]);
}
return $quantity + $childrenQuantity;
}
您可以像这样调用此函数:
$total = GetChildrenQuantity($yourArray[2772]);
如果您想以这种方式找到元素:
function FindElementIn($list, $id){
$element = null;
$quantity = count($list->children);
for($i=0;$i<$quantity;$i++){
if ($list->children[i]->post_id == $id)
return $element->children[i];
else {
$element = FindElementIn($list->children[i]->children, $id);
if ($element != null) return $element;
}
}
return null;
}