fork download
  1. <?php
  2.  
  3. function count_element_children(&$content){
  4.  
  5. if(!isset($content['children'])){
  6. return 1;
  7. }
  8. else{
  9. foreach($content['children'] as &$child){
  10. $content['children_count'] += count_element_children($child) + $child['children_count'];
  11. }
  12.  
  13. }
  14. }
  15.  
  16. $table = [
  17. 1 => [
  18. 'id' => 1,
  19. 'children_count' => 0
  20. ],
  21. 2 => [
  22. 'id' => 2,
  23. 'children_count' => 0,
  24. 'children' => [
  25. 3 => [
  26. 'id' => 3,
  27. 'children_count' => 0,
  28. 'children' => [
  29. 4 => [
  30. 'id' => 4,
  31. 'children_count' => 0,
  32. 'children' => [
  33. 5 => [
  34. 'id' => 5,
  35. 'children_count' => 0
  36. ],
  37.  
  38. 6 => [
  39. 'id' => 6,
  40. 'children_count' => 0
  41. ]
  42. ]
  43. ]
  44. ]],
  45. 7 => [
  46. 'id' => 7,
  47. 'children_count' => 0
  48. ],
  49.  
  50. ]
  51.  
  52. ]
  53. ];
  54.  
  55. foreach($table as &$element){
  56. if(isset($element['children'])) count_element_children($element);
  57. }
  58.  
  59. var_dump($table);
Success #stdin #stdout 0.02s 24448KB
stdin
Standard input is empty
stdout
array(2) {
  [1]=>
  array(2) {
    ["id"]=>
    int(1)
    ["children_count"]=>
    int(0)
  }
  [2]=>
  &array(3) {
    ["id"]=>
    int(2)
    ["children_count"]=>
    int(3)
    ["children"]=>
    array(2) {
      [3]=>
      array(3) {
        ["id"]=>
        int(3)
        ["children_count"]=>
        int(2)
        ["children"]=>
        array(1) {
          [4]=>
          array(3) {
            ["id"]=>
            int(4)
            ["children_count"]=>
            int(2)
            ["children"]=>
            array(2) {
              [5]=>
              array(2) {
                ["id"]=>
                int(5)
                ["children_count"]=>
                int(0)
              }
              [6]=>
              array(2) {
                ["id"]=>
                int(6)
                ["children_count"]=>
                int(0)
              }
            }
          }
        }
      }
      [7]=>
      array(2) {
        ["id"]=>
        int(7)
        ["children_count"]=>
        int(0)
      }
    }
  }
}