PHP code example of chastephp / array2tree

1. Go to this page and download the library: Download chastephp/array2tree library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chastephp / array2tree example snippets


$arr = [
    ['id' => 1, 'name' => '11', 'parent_id' => 0],
    ['id' => 2, 'name' => '22', 'parent_id' => 1],
    ['id' => 3, 'name' => '33', 'parent_id' => 2],
    ['id' => 4, 'name' => '44', 'parent_id' => 2],
];

var_dump(array2tree($arr, 'id', 'parent_id', 'children')); 


array (
  0 =>
  array (
    'id' => 1,
    'name' => '11',
    'parent_id' => 0,
    'children' =>
    array (
      0 =>
      array (
        'id' => 2,
        'name' => '22',
        'parent_id' => 1,
        'children' =>
        array (
          0 =>
          array (
            'id' => 3,
            'name' => '33',
            'parent_id' => 2,
            'children' =>
            array (
            ),
          ),
        ),
      ),
    ),
  ),
)