创建一个嵌套数组

ahmetkocabiyik

我有一个像下面的桌子

  • ID
    • 1个
    • 2个
    • 4
  • 标题
    • 主页
    • 关于
    • 审判
  • sl
    • 关于
    • 审判
  • 命令
    • 1个
    • 2个
    • 1个
  • 身体
    • 洛伦普本身
    • 点坐
    • 色差
  • parent_id
    • 2个
    • 0
    • 0

现在,我想从该表创建嵌套数组。我的功能如下

public function get_nested ()
{
    $pages = $this->db->get('pages')->result_array();
    $array = array();
    foreach ($pages as $page) {
        if (! $page['parent_id']) {
            $array[$page['id']] = $page;
        }
        else {
            $array[$page['parent_id']]['children'][] = $page;

        }
    }
    return $array;
}
dump($array);

当我转储我的$ array

Dump => array(2) {
[2] => array(6) {
["id"] => string(1) "2"
["title"] => string(5) "About"
["slug"] => string(5) "about"
["order"] => string(1) "2"
["body"] => string(241) "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam itaque cumque ullam eum atque consectetur voluptates veritatis sapiente voluptatem voluptatibus neque, commodi reprehenderit odit dignissimos omnis, veniam et deserunt incidunt!"
["parent_id"] => string(1) "0"
}
[4] => array(6) {
["id"] => string(1) "4"
["title"] => string(6) "deneme"
["slug"] => string(6) "deneme"
["order"] => string(1) "1"
["body"] => string(13) "deneme"
["parent_id"] => string(1) "0"
}
}

数组中只有2个页面列表,但是有3个页面,其中一个页面具有parent_id。没有显示具有parent_id的页面。因此,get_nested函数的else块中有一些错误。这是什么错误?

维维克·普拉塔普·辛格(Vivek Pratap Singh)

仔细查看您的代码,您将意识到它何时首次执行(for parent_id =2),

$array[$page['parent_id']]['children'][] = $page; 

它将发现$ array [2]($array [2] ['children'] [ ])不存在。可能的解决方案是SORT (OrderBy) your query in ascending order of parent_id.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

递归创建一个嵌套数组

PHP-通过嵌套数组创建一个新数组,同时创建一个post / image关系

Javascript数组,每次增加都创建一个嵌套数组

用javascript中的给定数组创建一个嵌套数组

在 angular-10 中递归地创建一个嵌套数组

JavaScript:创建将嵌套数组中的数据转换为具有多个对象的一个数组的函数

我想创建一个嵌套数组,它由另一个数组中的所有元素组成,但分为两个

$push 一个对象到一个嵌套数组

如何在mongodb的对象中更新我的另一个嵌套数组的嵌套数组

将嵌套数组类转换为另一个嵌套数组类 c#

如何在 MongoDB 中的另一个嵌套数组中更新嵌套数组中的对象

给定一个索引数组,从嵌套数组中获取适当的项

删除基于另一个数组的嵌套数组

将嵌套数组与另一个数组进行比较

numpy索引嵌套数组,其中包含来自另一个数组的索引

Vue 如何将嵌套数组合并为一个数组

如何在一个数组中有多个嵌套数组

使用另一个数组和PHP对嵌套数组进行排序

如何将嵌套数组推入一个数组中

将嵌套数组的元素合并为一个大数组

我想根据嵌套数组中的值返回一个多维数组

查找数组是否在另一个嵌套数组中

javascript循环嵌套数组并根据另一个数组提取属性

通过第一个元素合并嵌套数组和常规数组

通过 id 过滤一个数组,然后通过内部的嵌套数组进行映射

如何将两个数组合并为一个嵌套数组?

Spark:从Scala的嵌套数组中删除第一个数组

查找嵌套数组中的每个第一个数组

在一个表中创建嵌套数据的简化查询(.NET Core)