Skip to content

Instantly share code, notes, and snippets.

@lenivene
Last active September 16, 2019 14:03
Show Gist options
  • Save lenivene/dd257e2dd8724d2b4ec525ca89474f26 to your computer and use it in GitHub Desktop.
Save lenivene/dd257e2dd8724d2b4ec525ca89474f26 to your computer and use it in GitHub Desktop.
PHP: Create a array tree from array list

EXAMPLE

$list = array(
	array(
		'ID' => 1,
		'parent_id' => 0,
		'name' => 'Lenivene Bezerra'
	),
	array(
		'ID' => 2,
		'parent_id' => 1,
		'name' => 'Michael S. Carnahan'
	),
	array(
		'ID' => 3,
		'parent_id' => 2,
		'name' => 'Billy T. Nealon'
	)
);

$tree = inel_set_tree($list, 'parent_id', 'ID');

echo "<pre>";
var_dump( $tree );
<?php
/**
* Create a array tree from array list
*
* @param array ( Required ) The list to create tree
* @param string The name key parent. Ex: parent_id
* @param string The key to check child. Ex: ID
*
* @return array|false Returns array if the date given is not empty; otherwise returns FALSE.
*/
function inel_set_tree( $list, $PIDkey = 'parent_id', $IDkey = 'ID' ){
$children = [];
foreach( $list as $child ){
if( isset( $child[ $PIDkey ] ) ){
$children[ $child[ $PIDkey ] ][] = $child;
}
}
if( empty( $children ) )
return false;
list( $start_tree ) = $children;
$fn_set_tree = function( $brethren ) use ( &$fn_set_tree, $children, $IDkey ){
foreach( $brethren as $key => $brother ){
$ID = $brother [ $IDkey ];
if( isset( $children[ $ID ] ) )
$brother['children'] = $fn_set_tree( $children[ $ID ] );
$brethren[ $key ] = $brother;
}
return $brethren;
};
$tree = $fn_set_tree( $start_tree );
return $tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment