[英]Create a nested array
我有一个像下面的桌子
现在,我想从该表创建嵌套数组。 我的功能如下
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块中存在一些错误。 这是什么错误?
<?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);
?>
仔细查看您的代码,您将意识到它在首次执行时( 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.
进行SORT (OrderBy) your query in ascending order of parent_id.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.