我正在尝试将一组页面排列到一个数组中,并根据它们的父ID号放置它们。如果父 id 为 0,我希望它作为数组放置在数组中,如下所示......
$get_pages = 'DATABASE QUERY'
$sorted = array()
foreach($get_pages as $k => $obj) {
if(!$obj->parent_id) {
$sorted[$obj->parent_id] = array();
}
}
但是如果设置了父 id,我想将其放入相关数组中,再次作为这样的数组......
$get_pages = 'DATABASE QUERY'
$sorted = array()
foreach($get_pages as $k => $obj) {
if(!$obj->parent_id) {
$sorted[$obj->id] = array();
} else if($obj->parent_id) {
$sorted[$obj->parent_id][$obj->id] = array();
}
}
这就是我开始遇到问题的地方。如果我有一个需要插入数组第 2 维的第 3 个元素,甚至是需要插入第 3 维的第 4 个元素,我无法检查该数组键是否存在。所以我无法弄清楚的是,如何检测数组键是否存在于第一维之后,以及它是否存在于它的位置,以便我可以放置新元素。
这是我的数据库表的示例
id page_name parent_id
1 Products 0
2 Chairs 1
3 Tables 1
4 Green Chairs 2
5 Large Green Chair 4
6 About Us 0
这是我想获得的输出的示例,如果有更好的方法,我愿意接受建议。
Array([1]=>Array([2] => Array([4] => Array([5] => Array())), [3] => Array()), 6 => Array())
提前感谢!
好吧,本质上你正在构建一棵树,所以要走的方法之一是递归:
// This function takes an array for a certain level and inserts all of the
// child nodes into it (then going to build each child node as a parent for
// its respective children):
function addChildren( &$get_pages, &$parentArr, $parentId = 0 )
{
foreach ( $get_pages as $page )
{
// Is the current node a child of the parent we are currently populating?
if ( $page->parent_id == $parentId )
{
// Is there an array for the current parent?
if ( !isset( $parentArr[ $page->id ] ) )
{
// Nop, create one so the current parent's children can
// be inserted into it.
$parentArr[ $page->id ] = array();
}
// Call the function from within itself to populate the next level
// in the array:
addChildren( $get_pages, $parentArr[ $page->id ], $page->id );
}
}
}
$result = array();
addChildren( $get_pages, $result );
print_r($result);
这不是最有效的方法,但对于少量页面和层次结构,您应该没问题。