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

时间:2014-04-11 05:22:58

标签: php

你好我使用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
                            )
                    )
            )

    )

)

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:2)

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

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;
}

https://eval.in/145508