将分隔字符串(文件路径)的平面数组转换为分层的关联多维数组

问题描述 投票:0回答:3

我在这个巨大的平面单个数组中有一组键,我想基本上将该数组扩展为由键组织的多维数组 - 这是一个示例:

输入:

[
    'invoice/products/data/item1',
    'invoice/products/data/item2',
    'invoice/products/data/item2',
]

想要的结果:

[
    'invoice' => [
        'products' => ['item1', 'item2', 'item3']
    ]
]

我该怎么做?

上述字符串的长度是可变的。

php arrays multidimensional-array hierarchical-data directory-structure
3个回答
5
投票
$src = array(
'invoice/products/data/item1',
'invoice/products/data/item2',
'invoice/products/data/item2',
'foo/bar/baz',
'aaa/bbb'
);

function rsplit(&$v, $w)
{
    list($first, $tail) = explode('/', $w, 2);
    if(empty($tail)) 
    {
        $v[] = $first;
        return $v;
    }
    $v[$first] =  rsplit($v[$first], $tail);
    return $v;

}

$result = array_reduce($src, "rsplit");
print_r($result);

输出是:

Array (
    [invoice] => Array
        (
            [products] => Array
                (
                    [data] => Array
                        (
                            [0] => item1
                            [1] => item2
                            [2] => item2
                        )

                )

        )

    [foo] => Array
        (
            [bar] => Array
                (
                    [0] => baz
                )

        )

    [aaa] => Array
        (
            [0] => bbb
        )

)

2
投票

沿着这些思路:(虽然没有测试!)现在可以使用;)

$data = array();
$current = &$data;
foreach($keys as $value) {
  $parts = explode("/", $value);
  $parts_count = count($parts);
  foreach($parts as $i => $part) {
    if(!array_key_exists($part, $current)) {
      if($i == $parts_count - 1) {
        $current[] = $part;
      }
      else {
        $current[$part] = array();
        $current = &$current[$part];
      }
    }
    else {
      $current = &$current[$part];
    }
  }
  $current = &$data;
}

$keys 是平面数组。


0
投票

虽然从你的问题中不清楚“/”分隔的字符串如何映射到数组,但基本方法可能是这样的:

$result = array();
$k1 = $k2 = '';
ksort($yourData); // This is the key (!)
foreach ($yourData as $k => $v) {
  // Use if / else if / else if to watch for new sub arrays and change
  // $k1, $k2 accordingly
  $result[$k1][$k2] = $v;
}

这种方法使用 ksort 来确保同一“级别”的键出现在一起,如下所示:

'invoice/products/data1/item1'
'invoice/products/data1/item2'
'invoice/products/data2/item3'
'invoice/products2/data3/item4'
'invoice/products2/data3/item5'

注意 ksort 如何对应于您想要的键分组。

© www.soinside.com 2019 - 2024. All rights reserved.