gpt4 book ai didi

php - 数组中的嵌套页面 - PHP

转载 作者:搜寻专家 更新时间:2023-10-31 20:44:18 24 4
gpt4 key购买 nike

我正在为自定义 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
)

)

所以我希望接触出现在条件的 else 部分。我试过在条件下只回显“ parent ”和“ child ”并且它有效但是在写 $array[$page['parent_id']] 时什么也没有出现,甚至没有一个 block 说它是空的。我目前得到的回应是:

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] 内给我一个子数组,但那里什么也没有。我已经检查了数据库中 parent_id 的类型,它是 INT(11),所以应该不会产生问题。

提前致谢。

最佳答案

它将在您的数组中设置子项。但是这段代码有一个错误。当 child 出现在它的 parent 之前时,它会首先设置 child ,但是当 parent 在以下条件下出现在 child 之后时,您将覆盖 $array ..

if ( !$page['parent_id'] )
{
$array[$page['id']] = $page;
}

所以它不会保留已经设置的 child 。

你必须做这样的事情:

if ( !$page['parent_id'] )
{
if(!isset($array[$page['id']]))
$array[$page['id']] = $page;
else
$array[$page['id']] = array_merge($page,$array[$page['id']]);
}

然后它会保护 child 。让我知道这是否有效。


更新:我只是尝试在上述条件下运行您的程序...它给出的输出如下:

array
1 =>
array
'id' => int 1
'title' => string 'homepage' (length=8)
'parent_id' => int 0
4 =>
array
'id' => int 4
'title' => string 'about' (length=5)
'parent_id' => int 0
'children' =>
array
0 =>
array
'id' => int 3
'title' => string 'contact' (length=7)
'parent_id' => int 4

关于php - 数组中的嵌套页面 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15164018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com