$array_data = [
['id' => 1, 'parent_id' => 0],
['id' => 2, 'parent_id' => 1],
['id' => 3, 'parent_id' => 2],
['id' => 4, 'parent_id' => 3],
];
$parents = [];
$array_data_assoc = [];
foreach($array_data as $value){
$parents[$value['parent_id']][] = $value['id'];
$array_data_assoc[$value['id']] = $value;
}
function spread($array_data_assoc, $parents, $parent_id = 0){
$return = [];
if(array_key_exists($parent_id, $parents)){
foreach($parents[$parent_id] as $value){
$_value = $array_data_assoc[$value];
if(array_key_exists($value, $parents)){
$_value['parents'] = spread($array_data_assoc, $parents, $value);
}
$return[] = $_value;
}
}
return $return;
}
echo '<pre>', print_r(spread($array_data_assoc, $parents), true), '</pre>';