基于值嵌套数组项

时间:2017-03-01 12:18:18

标签: php arrays laravel laravel-4

我有一个这样的数组:

0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null],
1 => ['id'=> 2, 'name' => 'A', 'parent_id' => 1],
2 => ['id'=> 3, 'name' => 'A', 'parent_id' => 2],
3 => ['id'=> 4, 'name' => 'A', 'parent_id' => 2],
4 => ['id'=> 5, 'name' => 'A', 'parent_id' => 4]

我如何迭代这个以创建一个嵌套数组,其中项目基于其parent_id在彼此内部?

结果看起来像这样:

0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null, 'children' => [['id'=> 2, 'name' => 'A', 'parent_id' => 1, 'children' => [['id'=> 3, 'name' => 'A', 'parent_id' => 2], ['id'=> 4, 'name' => 'A', 'parent_id' => 2, 'children' => [['id'=> 4, 'name' => 'A', 'parent_id' => 4]]]]]]]

2 个答案:

答案 0 :(得分:1)

使用递归功能:

$arr = array(
0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null],
1 => ['id'=> 2, 'name' => 'A', 'parent_id' => 1],
2 => ['id'=> 3, 'name' => 'A', 'parent_id' => 1],
3 => ['id'=> 4, 'name' => 'A', 'parent_id' => 2],
);

function add_childs(array $elements, $parentId = null) {
    $parent = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
          echo "in if".$element['id']."<br>";
            $children = add_childs($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $parent[] = $element;
        }
    }

    return $parent;
}

$result = add_childs($arr);
print_r($result);

示例:https://eval.in/745350

答案 1 :(得分:0)

编辑:我理解其他方式的问题(父母附属于孩子)......

您必须遍历用户以查找每个父/子配对。

<?php
$users = [
0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null],
1 => ['id'=> 2, 'name' => 'B', 'parent_id' => 1],
2 => ['id'=> 3, 'name' => 'C', 'parent_id' => 2],
3 => ['id'=> 4, 'name' => 'D', 'parent_id' => 2],
3 => ['id'=> 4, 'name' => 'E', 'parent_id' => 4]
];

foreach($users as $user){
    foreach($users as &$parent){
        if($user['parent_id'] == $parent['id']){
            $parent['children'][] = $user;
        }
    }
}

var_dump($users);

?>