PHP:递归修改数组?

标签 php arrays multidimensional-array

我已经尝试创建一个函数来遍历以下数组以将其展平并在适用的情况下将父 ID 添加到子项。我只是无法让它工作,所以我希望这里的任何人都知道该怎么做:

这里是起点:

Array
(
    [0] => Array (
            [id] => 1
            [children] => array (
                [id] => 2
                [children] => Array (
                    [0] => Array (
                            [id] => 3
                    )
             )
        )
)

预期结果:

Array (

    [0] => array ( 
        [id] => 1
    )

    [1] => array ( 
        [id] => 2
    )

    [2] => array ( 
        [id] => 3,
        [parent] => 2
    ) 

)

希望任何人都可以指出我正确的方向。非常感谢!

解决方案(感谢 Oli!):

$output = array();

        function dejigg($in) {
            global $output;

            if (!isset($in['children'])) {
                $in['children'] = array();
            }
            $kids = $in['children'] or array();
            unset($in['children']);
            if (!isset($in['parent'])) {
                $in['parent'] = 0; // Not neccessary but makes the top node's parent 0.
            }
            $output[] = $in;

            foreach ($kids as $child) {
                $child['parent'] = $in['id'];
                dejigg($child); // recurse
            }

            return $output;
        }

        foreach ($array as $parent) {
            $output[] = dejigg($parent);
        }

        $array = $output;
        print("<pre>".print_r($array,true)."</pre>");

最佳答案

这次我测试过了。这确实有效!

$input = array( array('id' => 1, 'children'=>array( array('id'=>2, 'children'=>array( array('id'=>3) ) ) ) )  );
$output = [];

function dejigg($in) {
    global $output;

    $kids = $in['children'] or array();
    unset($in['children']);
    $output[] = $in;

    foreach ($kids as $child) {
        $child['parent'] = $in['id'];
        dejigg($child); // recurse
    }
}

foreach ($input as $parent)
    dejigg($parent);

print_r($output);

它返回:

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 3
            [parent] => 2
        )

)

关于PHP:递归修改数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999328/

相关文章:

python - Python多维Grid的生成

php - 有没有一种简单的方法可以将渲染网页中的部分保存为图像?

java - 如何将数组作为注释参数传递?

perl - 如何在Perl中初始化2D数组?

java - 在 Java 中使用分隔符(与拆分相反)连接数组元素的快速简便方法

python - Numpy 多维数组中的索引顺序

php - 如何在GoogleAnalytics API中获取单独页面的综合浏览量数据

php - 每个公共(public)属性都必须有访问器方法吗?

php - CodeIgniter Ajax 响应包含数据但输出未定义

Java编码问题