如何在递归中构建数组?

时间:2017-06-09 06:54:12

标签: php arrays recursion

我有以下结构数组:

array:6 [▼
  "593a4331b25f428814000035" => array:8 [▶]
  "593a4331b25f428814000036" => array:8 [▶]
  "593a4331b25f428814000037" => array:8 [▶]
  "593a4331b25f428814000038" => array:8 [▼
    "_id" => MongoId {#238 ▶}
    "object_id" => "593a4331b25f428814000034"
    "parameter_id" => "59398f5ab25f424016000029"
    "value" => "1"
    "children" => []
    "parent_id" => "593a4331b25f428814000037"
    "type" => "2"
    "prefix" => "object"
  ]
  "593a4331b25f428814000039" => array:8 [▶]
  "593a4331b25f42881400003a" => array:8 [▶]
]

正如您所看到的,数组的第3个元素具有父593a4331b25f428814000037,其中identifyicator是同一数组中的元素。

如何将这个元素593a4331b25f428814000038放在子元素中的父元素中?

结果我需要得到:

"593a4331b25f428814000037" => array:8 [▼
        "_id" => MongoId {#238 ▶}
        "object_id" => "593a4331b25f428814000034"
        "parameter_id" => "59398f5ab25f424016000029"
        "value" => "1"
        "children" => [ 0 => array("_id" => MongoId {#238 ▶}
        "object_id" => "593a4331b25f428814000034"
        "parameter_id" => "59398f5ab25f424016000029"
        "value" => "1"
        "children" => []
        "parent_id" => "593a4331b25f428814000037"
        "type" => "2"
        "prefix" => "object")]
        "parent_id" => "593a4331b25f428814000037"
        "type" => "2"
        "prefix" => "object"
      ]

我试过这种方式:

public function recursion($data){

foreach ($data as $k => $value) {

            if (is_array($value['children']) && count($value['children']) > 0) {

                $list[$k] = $value;
                $list[$k]["children"] = $this->getChildren($all, $value['children']);

            } else {

                $list[$k] = $value;
            }
        }

        return $list;
}


private function getChildren($all, $childs)
    {

        $list = [];

        foreach ($childs as $k => $child) {

            if (is_array($all[$child]['children'])) {

                $tmpArray = $all[$child];
                $tmpArray['children'] = $this->getChildren($all, $all[$child]['children']);

            } else {

                $tmpArray = $all[$child];
            }

            $list[] = $tmpArray;
        }

        return $list;

    }

但它的工作原理不正确

1 个答案:

答案 0 :(得分:0)

您可以使用array_reduce之类的:

$array = array_reduce($myArray, function ($carry, $item) {

    if (empty($item['parent_id'])) {
        $carry[$item['object_id']] = $item;
    } else {
        $carry[$item['parent_id']]['children'][] = $item;
    }
    return $carry;

}, []);

var_dump($array);

在这个例子中,我认为parent_id对于那些不属于另一个项目的项目是空的。如果没有isset密钥

,您可以使用parent_id进行更改