创建一个嵌套数组

时间:2014-08-18 08:35:13

标签: php arrays nested

我有一张如下表

  • ID
    • 1
    • 2
    • 4
  • 标题
      < li>主页
    • 关于
    • Deneme
  • slug
    • home
    • deneme
  • 顺序
    • 1
    • 2
    • 1
    • Loremp ipsum
    • Dot sit
    • Color amet
  • 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块中有一些错误。这个错误是什么?

2 个答案:

答案 0 :(得分:0)

<?php
try this:

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 if(isset($array[$page['parent_id']])){
            $size=sizeof($array[$page['parent_id']]);
            $array[$page['parent_id']][$size+1]= $page;

        }else{
            $array[$page['parent_id']]= $page;
        }
    }
        return $array;
    }
    dump($array);

?>

答案 1 :(得分:0)

彻底查看你的代码,你会意识到它首次执行时(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.