如何将多个字符串拆分为深层嵌套数组?

时间:2010-11-02 15:46:13

标签: php

我有多个类似于:

的字符串
$str = "/One/Two";
$str2 = "/One/Two/Flowers";
$str3 = "/One/Two/Grass";
$str4 = "/One/Another/Deeper";
$str5 = "/Uno/Dos/Cow";

我想将它拆分为一个深层嵌套数组,看起来类似于以下内容:

Array
(
    [One] => Array 
    (
        [Two] => Array
        (
            [Flowers] => 
            [Grass] => 
        )    
        [Another] => Array
        (
            [Deeper] => 
        )           
    )   
    [Uno] => Array 
    (
        [Dos] => Array
        (
            [Cow] => 
        )             
    )         
)

2 个答案:

答案 0 :(得分:5)

这应该这样做:

$strings = array(
    "/One/Two",
    "/One/Two/Flowers",
    "/One/Two/Grass",
    "/One/Another/Deeper",
    "/Uno/Dos/Cow"

);

$result = array();

foreach($strings as $string) {
    $parts = array_filter(explode('/', $string));

    $ref = &$result;
    foreach($parts as $p) {
        if(!isset($ref[$p])) {
            $ref[$p] = array();
        }
        $ref = &$ref[$p];
    }
    $ref = null;
}

print_r($result);

工作示例:

  

http://codepad.org/GmAoXLXp

答案 1 :(得分:1)

这样的事情应该有效。我无法想到构建结构的任何好的功能方法,所以我回到了几个foreach循环。

<?php

$strings = array(
    '/One/Two',
    '/One/Two/Flowers',
    '/One/Two/Grass',
    '/One/Another/Deeper',
    '/Uno/Dos/Cow'
);

$paths = array_map(
    function ($e) {
        return explode('/', trim($e, '/'));
    },
    $strings
);

$pathStructure = array();

foreach ($paths as $path) {
    $ref =& $pathStructure;
    foreach ($path as $dir) {
        $ref =& $ref[$dir];
    }
}
unset($ref);

print_r($pathStructure);