1

我的嵌套结构与文件夹结构非常相似,例如:

Array
(
    [level_one_1] => Array
        (
            [level_two_1] => value1
            [level_two_2] => valuetwo
            [level_two_3] => value_three
        )
    [level_one_2] => Array
        (
            [level_two_4] => value1
            [level_two_5] => valuetwo
            [level_two_6] => value_three
        )
    [level_one_3] => Array
        (
            [level_two_2] => valuetwo
            [level_two_3] => value_three
        )
)

是否可以快速将其转换为以下内容:

Array
(
    [level_one_1/level_two_1] => value1
    [level_one_1/level_two_2] => valuetwo
    [level_one_1/level_two_3] => value_three

    [level_one_2/level_two_4] => value1
    [level_one_2/level_two_5] => valuetwo
    [level_one_2/level_two_6] => value_three)

    [level_one_3/level_two_2] => valuetwo
    [level_one_3/level_two_3] => value_three
)

级别之间的斜线将是分隔符 - 它可以是任何东西。它也将是动态的级别数。

是否可以通过使用预定义的 array* 函数来做到这一点?用递归?

4

1 回答 1

1

像这样的东西。未经测试,但应该可以帮助您朝着正确的方向开始:

$myArray = array(
'level_one_1' => array(
        'level_two_1' => 'value1',
        'level_two_2' => 'valuetwo',
        'level_two_3' => 'value_three'
),
'level_one_2' => array(
        'level_two_4' => 'value1',
        'level_two_5' => 'valuetwo',
        'level_two_6' => 'value_three'
),
'level_one_3' => array(
        'level_two_2' => 'valuetwo',
        'level_two_3' => 'value_three'
));
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray));
$result = array();
foreach ($ritit as $leafValue) {
    $keys = array();
    foreach (range(0, $ritit->getDepth()) as $depth) {
        $keys[] = $ritit->getSubIterator($depth)->key();
    }
    $result[ join('/', $keys) ] = $leafValue;
}
于 2012-05-08T04:25:16.027 回答