fork download
  1. <?php
  2.  
  3. $entrada = array(
  4. array(col_1=>190, col_2=>340),
  5. array(col_1=>190, col_2=>54),
  6. array(col_1=>10, col_2=>20),
  7. array(col_1=>20, col_2=>40),
  8. array(col_1=>20, col_2=>50),
  9. array(col_1=>10, col_2=>30),
  10. );
  11.  
  12. $name = "name";
  13. $children = "children";
  14. $var = array();
  15.  
  16. asort($entrada);
  17.  
  18. $ultimo = null;
  19. foreach($entrada as $colunas) {
  20. if ( is_null($ultimo) || $ultimo[$name] != $colunas["col_1"] ) {
  21. if ( !is_null($ultimo) )
  22. array_push($var, $ultimo);
  23. $ultimo = array($name=>$colunas["col_1"], $children=>array());
  24. }
  25. $ultimo[$children][] = array($name => $colunas["col_2"]);
  26. }
  27. if ( !is_null($ultimo) )
  28. $var[] = $ultimo;
  29.  
  30. $ip = json_encode($var, JSON_PRETTY_PRINT);
  31.  
  32. echo $ip;
Success #stdin #stdout #stderr 0.01s 20568KB
stdin
Standard input is empty
stdout
[
    {
        "name": 10,
        "children": [
            {
                "name": 20
            },
            {
                "name": 30
            }
        ]
    },
    {
        "name": 20,
        "children": [
            {
                "name": 40
            },
            {
                "name": 50
            }
        ]
    },
    {
        "name": 190,
        "children": [
            {
                "name": 54
            },
            {
                "name": 340
            }
        ]
    }
]
stderr
PHP Notice:  Use of undefined constant col_1 - assumed 'col_1' in /home/Qno9F2/prog.php on line 4
PHP Notice:  Use of undefined constant col_2 - assumed 'col_2' in /home/Qno9F2/prog.php on line 4
PHP Notice:  Use of undefined constant col_1 - assumed 'col_1' in /home/Qno9F2/prog.php on line 5
PHP Notice:  Use of undefined constant col_2 - assumed 'col_2' in /home/Qno9F2/prog.php on line 5
PHP Notice:  Use of undefined constant col_1 - assumed 'col_1' in /home/Qno9F2/prog.php on line 6
PHP Notice:  Use of undefined constant col_2 - assumed 'col_2' in /home/Qno9F2/prog.php on line 6
PHP Notice:  Use of undefined constant col_1 - assumed 'col_1' in /home/Qno9F2/prog.php on line 7
PHP Notice:  Use of undefined constant col_2 - assumed 'col_2' in /home/Qno9F2/prog.php on line 7
PHP Notice:  Use of undefined constant col_1 - assumed 'col_1' in /home/Qno9F2/prog.php on line 8
PHP Notice:  Use of undefined constant col_2 - assumed 'col_2' in /home/Qno9F2/prog.php on line 8
PHP Notice:  Use of undefined constant col_1 - assumed 'col_1' in /home/Qno9F2/prog.php on line 9
PHP Notice:  Use of undefined constant col_2 - assumed 'col_2' in /home/Qno9F2/prog.php on line 9