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

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

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 ?

图片转代码服务由CSDN问答提供 功能建议

我有一个像 brachA-branchB-branchC 这样的字符串。 我试图将它作为嵌套数组,如下所示

  [
'name'=&gt;'brachA',
'sub'=&gt;  [
'name'=&gt;'brachB',
'sub'=&gt; [
'name'=&gt;'brachC'
] 
] 
] 
   
 
 

我尝试如下( https://3v4l.org/A781D

 &lt;?php 
 $ nested_array = array(); 
 $ temp =&amp; $ nested_array; 
 $ item ='brachA-branchB-branchC';  
 
foreach(explode(' - ',$ item)为$ key =&gt; $ value){
 $ temp =&amp; $ temp [$ value]; 
} 
 
print_r($ nested_array);  
   
 
 

输出我得到如下

  Array 
(
 [brachA] =&gt;数组 
(
 [branchB] =&gt;数组
(
 [branchC] =&gt; 
)
 
)
 
)
   
 
  

任何想法,如何实现这一目标?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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').

    打赏 评论

相关推荐 更多相似问题