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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?