简体   繁体   English

将平面数组转换为多维数组

[英]Convert flat array to the multi-dimensional

I have an array with tree data (by parent id). 我有一个带有树数据的数组(通过父ID)。 I want to convert it to multidimensional array. 我想将其转换为多维数组。 What is the best way to achieve that? 实现这一目标的最佳方法是什么? Is there any short function for that? 那有什么短暂的功能吗?

Source array: 源数组:

$source = array(
    '0' => array(
            'Menu' => array(
                    'id' => 45
                    'name' => 'Home'
                    'parent_id' => 1
            )
    )
    '1' => array(
            'Menu' => array(
                    'id' => 47
                    'name' => 'Get started'
                    'parent_id' => 1
            )
    )
    '2' => array(
            'Menu' => array(
                    'id' => 72
                    'name' => 'Attributes'
                    'parent_id' => 71
            )
    )
    '3' => array(
            'Menu' => array(
                    'id' => 73
                    'name' => 'Headings'
                    'parent_id' => 71
            )
    )
    '4' => array(
            'Menu' => array(
                    'id' => 75
                    'name' => 'Links'
                    'parent_id' => 71
            )
    )
    '5' => array(
            'Menu' => array(
                    'id' => 59
                    'name' => 'Images'
                    'parent_id' => 75
            )
    )
    '6' => array(
            'Menu' => array(
                    'id' => 65
                    'name' => 'Lists'
                    'parent_id' => 75
            )
    )
);

Some parents are missing from the source array. 源阵列中缺少一些父母。 I would like the items with missing parent to be root. 我希望缺少父项的项目是root。 Result array: 结果数组:

$result = array(
    '0' => array(
            'Menu' => array(
                    'id' => 45
                    'name' => 'Home'
                    'parent_id' => 1
            )
            'Children' => array()
    )
    '1' => array(
            'Menu' => array(
                    'id' => 47
                    'name' => 'Get started'
                    'parent_id' => 1
            )
            'Children' => array()
    )
    '2' => array(
            'Menu' => array(
                    'id' => 72
                    'name' => 'Attributes'
                    'parent_id' => 71
            )
            'Children' => array()
    )
    '3' => array(
            'Menu' => array(
                    'id' => 73
                    'name' => 'Headings'
                    'parent_id' => 71
            )
            'Children' => array()
    )
    '4' => array(
            'Menu' => array(
                    'id' => 75
                    'name' => 'Links'
                    'parent_id' => 71
            )
            'Children' => array(
                    '0' => array(
                        'Menu' => array(
                            'id' => 59
                            'name' => 'Images'
                            'parent_id' => 75
                        )
                        'Children' => array()
                    )
                    '1' => array(
                        'Menu' => array(
                            'id' => 65
                            'name' => 'Lists'
                            'parent_id' => 75
                        )
                        'Children' => array()
                   )
            )
     )
);

Update: removed square brackets. 更新:删除方括号。

I don't think there is a built-in function in PHP that does this. 我不认为PHP中有内置函数可以做到这一点。

I tried the following code, and it seems to work to prepare the nested array the way you describe: 我尝试了以下代码,它似乎可以按照您描述的方式准备嵌套数组:

$nodes = array();
$tree = array();
foreach ($source as &$node) {
  $node["Children"] = array();
  $id = $node["Menu"]["id"];
  $parent_id = $node["Menu"]["parent_id"];
  $nodes[$id] =& $node;
  if (array_key_exists($parent_id, $nodes)) {
    $nodes[$parent_id]["Children"][] =& $node;
  } else {
    $tree[] =& $node;
  }
}

var_dump($tree);

I wrote a similar algorithm in a PHP class I wrote for my presentation Hierarchical Models in SQL and PHP , but I was using objects instead of plain arrays. 我在我为SQL和PHP演示的Hierarchical Models中编写的PHP类中编写了类似的算法,但我使用的是对象而不是普通数组。

I wrote this variant considering root parent_id is 0 or missing. 考虑到root parent_id为0或缺少,我写了这个变体。 No matter children after parents in DB ($source) or not. 无论是父母在DB($ source)之后的孩子。

$source_by_id = array();
foreach ($source as &$row){
  $source_by_id[$row['id']] = &$row;
}
foreach ($source_by_id as $id => &$row){
  $source_by_id[ intval($row['parent_id']) ]['children'][$id] = &$row;
}
// remove cycling itself
unset($source_by_id[0]['children'][0]);

$result = $source_by_id[0]['children'];

Result array keys are appropriate ids. 结果数组键是适当的ID。 Enjoy! 请享用!

I was looking for an example of how to do this, with categories. 我正在寻找一个如何使用类别来做这个的例子。 This example assumes that parents will always have a parent id of '0'. 此示例假定父项的父ID始终为“0”。 The example is using ZF2. 该示例使用ZF2。

No references, or recursion. 没有引用或递归。 The trick is in the output, you look for the [0] index, and for the children, you specify the parent_id as the index. 技巧是在输出中,您查找[0]索引,对于子项,您将parent_id指定为索引。

$categoryLookup = $this->getCategoryLookup($associateById=true);

if ($assignedCategories) {          
    $categoryHeirarchy = array();
    foreach($assignedCategories as $assignedCategory) {
        $child = $categoryLookup[$assignedCategory->category_id];
        $parent = $categoryLookup[$child->parent_id];               
        $categoryHeirarchy[$child->parent_id][] = $categoryLookup[$child->category_id];
        $categoryHeirarchy[$parent->parent_id][$parent->category_id] = $categoryLookup[$parent->category_id];
    }           

    return $categoryHeirarchy;  
}


<h3>Categories</h3>
<dl class="dl-horizontal">
    <?php foreach($this->categoryHeirarchy[0] as $parent): ?>
        <dt><?php echo $this->escapeHtml($parent->name); ?></dt>
        <?php foreach($this->categoryHeirarchy[$parent->category_id] as $child): ?>
            <dd><?php echo $this->escapeHtml($child->name); ?></dd>
        <?php endforeach; ?>
    <?php endforeach; ?>                    
</dl>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM