【问题标题】:How to build an array in recursion?如何以递归方式构建数组?
【发布时间】:2017-06-09 06:54:12
【问题描述】:

我有如下结构数组:

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,其中标识符是同一数组中的元素。

如何将 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;

    }

但它工作不正确

【问题讨论】:

    标签: php arrays recursion


    【解决方案1】:

    您可以使用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 对于那些不属于另一个项目的项目是空的。如果没有parent_id 键,您可以使用isset 更改它

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 2017-04-25
      • 1970-01-01
      • 2020-09-21
      • 2020-03-13
      • 2015-06-12
      • 2022-09-27
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多