将数组重组为关联数组

时间:2018-04-27 13:58:28

标签: php associative-array

我有一个问题是从普通数组(列表)建立一个关联数组。

我有这个:


    $array = [
           't1/t1sub', 
           't1/t2sub', 
           't2/t1sub', 
           't3/t1sub', 
           't1/t4sub', 
           't4', 
           't1/t2sub/t1subsub', 
           't1/t2sub/t2subsub'
    ];

现在我想要这个:


    $target = [
        "t1" => [
            "t1sub",
            "t2sub" => [
                    "t1subsub",
                    "t2subsub"
            ],             
            "t4sub",
        ],
        "t2" => [
            "t1sub",
        ],
        "t3" => [
            "t1sub",
        ],
        "t4"
    ]

感谢帮助。

2 个答案:

答案 0 :(得分:0)

您可以在已经开始的循环中执行此操作。

$target = [];

foreach ($array as $item) {
    list($key, $value) = explode('/', $item);

    if (!isset($target[$key])) {
        $target[$key] = [$value];
    } else {
        $target[$key][] = $value;
    }
}

var_dump($target);

答案 1 :(得分:0)

你只需将元素切成两半,然后将后半部分推到上半部分键入的子阵列中。

代码(Demo

$array = ['t1/t1sub', 't1/t2sub', 't2/t1sub', 't3/t1sub', 't1/t4sub'];
foreach ($array as $v) {
    $x = explode("/", $v);
    $result[$x[0]][] = $x[1];
}
var_export($result);

输出:

array (
  't1' => 
  array (
    0 => 't1sub',
    1 => 't2sub',
    2 => 't4sub',
  ),
  't2' => 
  array (
    0 => 't1sub',
  ),
  't3' => 
  array (
    0 => 't1sub',
  ),
)