php - 数组键存在于多维数组中

标签 php arrays multidimensional-array array-key-exists

我正在尝试将一组页面排列到一个数组中,并根据其父 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/

相关文章:

Java,如何检查两个二维数组是否包含相同的值

php - 不能再在 Magento 1.4.2.0 中添加注册字段

PHP脚本没有插入到pg数据库

php - 如何在 Codeigniter 中基于表中按钮的 onclick 使用 jQuery 实现 show() hide() 函数?

php - 全局 php 文件

objective-c - NSArray 和 bool 值

java - 为什么我的数组搜索在搜索循环超过 2000 次后花费了 0 纳秒?

javascript - 将具有数组属性的对象展平为一个数组的最佳方法

java - 标签二维数组 | JavaFX

php - 如何使用 PHP 和 CURL 使用多维 POSTFIELDS 上传文件(多部分/表单数据)?