2014-12-15 4 views
0

아래는 제가 가지고있는 배열의 구조입니다. 두 가지 질문이 있습니다.배열 내의 자식 배열 수를 계산하십시오.

  1. 배열 내에서 배열의 위치는 어떻게 얻을 수 있습니까?

예를 들어 [post_id] => 2782 요소가있는 배열의 위치를 ​​얻으려면 [2772] => Array (대답은 4 여야합니다)입니까?

  1. 배열 내에서 하위 배열 수를 얻으려면 어떻게해야합니까?

예를 들어 요소가 [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

@ Ja͢ck : 나는 사용자가 3866797이라고 생각합니다. 깊은 곳이야? –

+0

중복 된 http://stackoverflow.com/questions/262891/is-there-a-way-to-find-out-how-deep-a-php-array-is – developerwjk

+0

@developerwjk 두 가지 질문이 있습니다. one ... –

답변

0

이 기능을 모든 아이를 셀 수 있습니다 : 당신이 요소가이 방법을 사용 찾으려면

$total = GetChildrenQuantity($yourArray[2772]); 

:

function GetChildrenQuantity($element){ 
    $quantity = count($element->children); 

    $childrenQuantity = 0; 
    for($i=0;$i<$quantity;$i++){ 
     $childrenQuantity += GetChildrenQuantity($element->children[i]); 
    } 

    return $quantity + $childrenQuantity; 

} 

당신은이 같은이 함수를 호출 할 수 있습니다

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; 

} 
관련 문제