Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中将一个索引的数据添加到同一数组的另一个索引中_Php - Fatal编程技术网

在php中将一个索引的数据添加到同一数组的另一个索引中

在php中将一个索引的数据添加到同一数组的另一个索引中,php,Php,您好,我使用laravel和magento DB来获取数据,我想制作以下数据的树状结构。最初我得到的数据是这样的 Array ( [parent] => Array ( [0] => Array ( [entity_id] => 5740 [name] => Sports [parent_id] => 5739

您好,我使用laravel和magento DB来获取数据,我想制作以下数据的树状结构。最初我得到的数据是这样的

Array
(
   [parent] => Array
        (
        [0] => Array
            (
                [entity_id] => 5740
                [name] => Sports
                [parent_id] => 5739
            )

        [1] => Array
            (
                [entity_id] => 6057
                [name] => Football
                [parent_id] => 5740
            )

        [2] => Array
            (
                [entity_id] => 6058
                [name] => American
                [parent_id] => 6057
            )

    )

)
我希望在我的应用程序中使用以下格式的上述数据

Array
(
  [parent] => Array
    (
            [0] => Array
            (
                    [entity_id] => 5740
                    [name] => Sports
                    [parent_id] => 5739
                    [child] => Array
                    (
                            [entity_id] => 6057
                            [name] => Football
                            [parent_id] => 5740
                            [child]=> Array
                            (
                                    [entity_id] => 6058
                                    [name] => American
                                    [parent_id] => 6057
                            )
                    )
            )

    )

)

谁能帮我一下吗

处理无序层次结构的解决方案

function hierarchize($data){
    $parentLess = [];
    $map = [];

    foreach($data['parent'] as &$entity){
        $id = $entity['entity_id'];
        $parentId = $entity['parent_id'];

        $map[$id] = &$entity;

        if(isset($map[$parentId])){
            $map[$parentId]['child'][] = &$entity;
        }else{
            $parentLess[$parentId][] = &$entity;
        }

        if(isset($parentLess[$id])){
            $entity['child'] = &$parentLess[$id];
            unset($parentLess[$id]);
        }
    }

    return $parentLess;
}

您可能需要发布您的模型关系和代码,以实际获取数据,从而获得准确答案。