dongyi1996 2017-10-06 11:21
浏览 23
已采纳

使用分隔符从字符串创建嵌套数组

I has a string like as brachA-branchB-branchC. I am trying to make it as nested array as follows

 [
    'name'=>'brachA',
    'sub'=> [
             'name'=>'brachB',
             'sub'=>[
                 'name'=>'brachC'
               ]
            ]
 ]

I tried as follows (https://3v4l.org/A781D)

<?php
$nested_array = array();
$temp = &$nested_array;
$item = 'brachA-branchB-branchC';

foreach (explode('-', $item) as $key => $value) {
      $temp = &$temp[$value];
}

print_r($nested_array);

Output I am getting as follows

Array
(
    [brachA] => Array
        (
            [branchB] => Array
                (
                    [branchC] => 
                )

        )

)

Any idea, how to achieve this ?

  • 写回答

1条回答 默认 最新

  • doutang9037 2017-10-06 11:31
    关注

    It can probably be done using a foreach loop over the reversed array returned by explode() but it is much easier to use a recursive function.

    function makeArray(array $pieces)
    {
        $first = array_shift($pieces);
    
        $array = array('name' => $first);
        if (count($pieces)) {
            $array['sub'] = makeArray($pieces);
        }
    
        return $array;
    }
    
    $item = 'brachA-branchB-branchC';
    print_r(makeArray(explode('-', $item)));
    

    The makeArray() function receives an array with the string pieces. It puts the first item under the 'name' key of a new array and invokes itself with the rest of the array to generate the array to put under the 'sub' key. It doesn't put anything for the 'sub' key if there is no rest (on the last call, $pieces is array('brachC').

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置