将嵌套结构转换为平键值对

时间:2012-05-08 04:13:48

标签: php arrays recursion breadcrumbs

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

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
)

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

使用预定义的数组*函数是否可以这样做?递归?

1 个答案:

答案 0 :(得分: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;
}