regwergewrg - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of regwergewrg.php

  1. <?php
  2. error_reporting(E_ERROR);
  3. $tree = '{"name": "A","items" : [{"name": "B","items" : [{"name": "D"},{"name": "E","items" : [{"name": "G"}]}]},{"name": "C","items" : [{"name": "F","items" : [{"name": "H"},{"name": "I"}]}]}]}';
  4. $tree = json_decode($tree, 1);
  5.  
  6. treeTraversal($tree);
  7.  
  8. function treeTraversal(&$tree)
  9. {
  10.     if (!$tree['items']) {
  11.         return;
  12.     }
  13.  
  14.     $tree['children'] = count($tree['items']);
  15.  
  16.     foreach ($tree['items'] as &$item) {
  17.         if ($cnt = treeTraversal($item)) {
  18.             $item['count'] = $cnt;
  19.         }
  20.     }
  21.  
  22.     $tree['count'] = array_sum(array_column($tree['items'], 'count')) + $tree['children'];
  23.  
  24.     return $tree['count'];
  25.  
  26. }
  27.  
  28. print_r($tree);
  29.  
File Description
  • regwergewrg
  • PHP Code
  • 21 Oct-2021
  • 690 Bytes
You can Share it: