<?php
/**
* Created by PhpStorm.
* User: liupf
* Date: 18-8-30
* Time: 下午11:44
*/
function arrayConvertToTree ($array, $rootId) {
$group = [];
$map = [];
foreach ($array as $val) {
$group[$val['parent_id']][] = $val;
$map[$val['id']] = [
$val['parent_id'],
count($group[$val['parent_id']]) - 1
];
}
foreach ($group as $key => &$val) {
if (!empty($map[$key])) {
$pos = $map[$key];
$group[$pos[0]][$pos[1]]['children'] = &$val;
}
}
return $group[$rootId];
}
$raw_data = [
[
'id' => 1,
'parent_id' => 0,
'value' => 1,
'children' => []
],
[
'id' => 2,
'parent_id' => 1,
'value' => 2,
'children' => []
],
[
'id' => 3,
'parent_id' => 1,
'value' => 3,
'children' => []
],
[
'id' => 4,
'parent_id' => 2,
'value' => 4,
'children' => []
],
[
'id' => 5,
'parent_id' => 2,
'value' => 5,
'children' => []
],
[
'id' => 6,
'parent_id' => 3,
'value' => 6,
'children' => []
],
[
'id' => 7,
'parent_id' => 3,
'value' => 7,
'children' => []
],
[
'id' => 8,
'parent_id' => 4,
'value' => 8,
'children' => []
],
[
'id' => 7,
'parent_id' => 4,
'value' => 7,
'children' => []
]
];
$tree = arrayConvertToTree($raw_data, 0);
print_r($tree);