本文介绍了计算数组中子数组的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我拥有的数组的结构.我有两个问题:
Below is the structure of an array I have. I have two questions:
- 如何获取数组在数组中的位置?
例如,如何获取元素为 [post_id] =>的数组的位置?
(答案应该是4)? [2772] =>中的2782
数组
For example, how would I get the position of array with element [post_id] => 2782
within [2772] => Array
(the answer should be 4)?
- 如何获取数组中子数组的数量?
例如,我如何获取元素为 [post_id] =>的数组的子数组数量.2779
(答案应该是2)?
For example, how would I get the number of children arrays for the array with element [post_id] => 2779
(the answer should be 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
(
)
)
)
)
)
推荐答案
您可以使用此功能计算所有孩子:
You can count all children with this function:
function GetChildrenQuantity($element){
$quantity = count($element->children);
$childrenQuantity = 0;
for($i=0;$i<$quantity;$i++){
$childrenQuantity += GetChildrenQuantity($element->children[i]);
}
return $quantity + $childrenQuantity;
}
您可以这样调用此函数:
You can call this function like this:
$total = GetChildrenQuantity($yourArray[2772]);
如果要查找元素,请使用以下方式:
If you want to find an element use this way:
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;
}
这篇关于计算数组中子数组的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!