-1

给定以下输入:

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
            )
    }
 )
4

2 回答 2

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
                )

        )

)
于 2013-07-26T05:24:37.107 回答
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);
于 2013-07-26T05:04:36.430 回答