将平面反向数组化 [英] Reverse flatted array to multidimensional

查看:59
本文介绍了将平面反向数组化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个线程中,我询问了如何将具有特定样式的数组展平得到这样的东西:

In another thread i asked about flatten an array with a specific style to get something like this:

array(4) {
  ["one"]=> string(9) "one_value"
  ["two-four"]=> string(10) "four_value"
  ["two-five"]=> string(10) "five_value"
  ["three-six-seven"]=> string(11) "seven_value"
}

我在这里有很好的帮助,但现在我想知道如何反转该方法以再次获得相同的原始数组:

I've got some very good help there, but now im wondering how would i reverse this method to get again the same original array:

array(
    'one' => 'one_value',
    'two' => array
        (
            'four' => 'four_value',
            'five' => 'five_value'
        ),

    'three' => array
        (
            'six' => array
                (
                    'seven' => 'seven_value'
                )

        )
)

我尝试了递归方法,但是没有运气。
我预先感谢所有帮助!

I've tried with recursive method but with no luck. I thank all the help in advance!

推荐答案

function expand($flat) {
    $result = array();
    foreach($flat as $key => $val) {
        $keyParts = explode("-", $key);
        $currentArray = &$result;
        for($i=0; $i<count($keyParts)-1; $i++) {
            if(!isSet($currentArray[$keyParts[$i]])) {
                $currentArray[$keyParts[$i]] = array();
            }
            $currentArray = &$currentArray[$keyParts[$i]];
        }
        $currentArray[$keyParts[count($keyParts)-1]] = $val;
    }
    return $result;
}

请注意,上面的代码未经测试,仅用于举例说明。
& 运算符用于 $ currentArray 来存储值而不是引用某些节点在您的树中(由多维数组实现),因此更改 $ currentArray 也会更改 $ result

Note that the code above is not tested and is given only to illustrate the idea. The & operator is used for $currentArray to store not the value but the reference to some node in your tree (implemented by multidimensional array), so that changing $currentArray will change $result as well.

这篇关于将平面反向数组化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆