在PHP中将平面数组转换为嵌套数组

时间:2013-07-26 04:32:08

标签: php flatten multidimensional-array

给出以下输入:

array('one/two/3',
      'one/four/0/5',
      'one/four/1/6',
      'one/four/2/7',
      'eight/nine/ten/11')

如何将其转换为:

array(
   'one': array( 
        'two': 3,
        'four': array(5,6,7)
    )
   'eight': array(
        'nine': (
                'ten':11
            )
    }
 )

2 个答案:

答案 0 :(得分:1)

$input = array ('one/two/3',
    'one/four/0/5',
    'one/four/1/6',
    'one/four/2/7',
    'eight/nine/ten/11');

$result = array ();
foreach ($input as $string) {
    $data      = array_reverse(explode('/', $string));
    $tmp_array = array ();
    foreach ($data as $val) {
        if (empty($tmp_array)) {
            $tmp_array = $val;
        } else {
            $tmp             = $tmp_array;
            $tmp_array       = array ();
            $tmp_array[$val] = $tmp;
        }
    }
    $result = array_merge_recursive($result, $tmp_array);
}
echo "<pre>";
print_r($result);
echo "</pre>";

输出:

Array
(
    [one] => Array
        (
            [two] => 3
            [four] => Array
                (
                    [0] => 5
                    [1] => 6
                    [2] => 7
                )

        )

    [eight] => Array
        (
            [nine] => Array
                (
                    [ten] => 11
                )

        )

)

答案 1 :(得分:0)

如果我们看到你尝试过的东西会很好。

$my_array = array('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11');

$result= array();   
foreach ($my_array as $val) {
$ref = & $result;
foreach (explode("/", $val) as $val) {
    if (!isset($ref[$val])) {
        $ref[$val] = array();
    }
    $ref = & $ref[$val];
}
$ref = $val;
}

var_dump($result);