我正在尝试将一组页面排列到一个数组中,并根据其父 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();
}
}
这就是我开始遇到问题的地方。如果我有一个需要插入到数组的第二个维度的第三个元素,或者甚至需要插入到第三个维度的第四个元素,我无法检查该数组键是否存在。所以我不知道如何检测第一个维度之后是否存在数组键以及它是否存在,以便我可以放置新元素。
这是我的数据库表的示例
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())
提前致谢!
最佳答案
好吧,本质上你正在构建一棵树,所以其中一种方法是使用 recursion :
// 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);
这不是最有效的方法,但对于少量页面和层次结构来说应该没问题。
关于php - 数组键存在于多维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10278070/