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

发布于 2024-09-10 06:45:45 字数 3359 浏览 2 评论 0原文

我有一个包含树数据的数组(按父 ID)。我想将其转换为多维数组。实现这一目标的最佳方法是什么?有没有什么短函数可以做到这一点?

源数组:

$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
            )
    )
);

源数组中缺少一些父项。我希望缺少父项的项目成为根。结果数组:

$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()
                   )
            )
     )
);

更新:删除了方括号。

I have an array with tree data (by parent 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. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一场信仰旅途 2024-09-17 06:45:45

我认为 PHP 中没有内置函数可以做到这一点。

我尝试了以下代码,它似乎可以按照您描述的方式准备嵌套数组:

$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);

我在为演示文稿编写的 PHP 类中编写了类似的算法 SQL 和 PHP 中的分层模型,但我使用的是对象而不是普通数组。

I don't think there is a built-in function in PHP that does this.

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.

青巷忧颜 2024-09-17 06:45:45

我编写此变体时考虑到 rootparent_id 为 0 或丢失。无论父母之后的孩子是否在 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'];

结果数组键是适当的 id。享受!

I wrote this variant considering root parent_id is 0 or missing. No matter children after parents in DB ($source) or not.

$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. Enjoy!

寒冷纷飞旳雪 2024-09-17 06:45:45

我正在寻找如何使用类别来执行此操作的示例。此示例假设父母的父母 ID 始终为“0”。该示例使用 ZF2。

没有引用,也没有递归。诀窍在于输出中,您查找 [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>

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'. The example is using 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.

$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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文