我有一张如下表
现在,我想从这个表创建嵌套数组。我的功能如下
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块中有一些错误。这个错误是什么?
答案 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.