我正在为自定义 CMS 检索数据库中的所有页面。页面是嵌套的,并且有 parent_id 来查找父页面的子页面。
检索代码的代码是:
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;
}
由于某种原因,else 条件不适用于 $array[$page['parent_id']]。
$pages 的转储给了我
Array
(
[0] => Array
(
[id] => 1
[title] => Homepage
[slug] => /
[order] => 1
[body] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
[parent_id] => 0
)
[1] => Array
(
[id] => 3
[title] => Contact
[slug] => contact
[order] => 0
[body] => <p>This is my contact page.</p>
[parent_id] => 4
)
[2] => Array
(
[id] => 4
[title] => About
[slug] => about
[order] => 0
[body] => <p>All about our company.</p>
[parent_id] => 0
)
)
所以我期待联系出现在条件的其他部分。我已经尝试在条件中回显“父”和“子”并且它可以工作,但是在编写 $array[$page['parent_id']] 时什么都没有出现,甚至没有一个块说它是空的。我目前得到的回应是:
Array
(
[1] => Array
(
[id] => 1
[title] => Homepage
[slug] => /
[order] => 1
[body] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
[parent_id] => 0
)
[4] => Array
(
[id] => 4
[title] => About
[slug] => about
[order] => 0
[body] => <p>All about our company.</p>
[parent_id] => 0
)
)
有谁知道为什么 $array[$page['parent_id']] 没有做任何事情?我认为它会在 [4] 内给我一个 children 数组,但那里什么都没有。我已经检查了数据库中 parent_id 的类型,它是 INT(11),所以不应该造成问题。
提前致谢。