Create variable length array from string

后端 未结 2 1448
我在风中等你
我在风中等你 2021-01-28 10:12

The string

$string = \'a.b.c.d\';

should create an array like

array(\'a\' => array(\'b\' => array( ....

I managed

相关标签:
2条回答
  • 2021-01-28 10:58

    This should work:

    function create_array(&$arr,$string,$data){
        $a=explode('.',$string);
        $last=count($a)-1;
        $p=&$arr;
    
        foreach($a as $k=>$key){
            if ($k==$last) {
                $p[$key]=$data; 
            } else if (is_array($p)){
                $p[$key]=array();
            }
            $p=&$p[$key];
        }
    }
    
    0 讨论(0)
  • 2021-01-28 11:15

    It's still pretty unclear, but if you only want what you have asked for:

    function convertToArray($string)
    {
        $pos = strpos($string, '.');
        $key = substr($string, 0, $pos);
    
        $result = array($key => array());
    
        if ($pos === false) {
            return array($string=>array());
        } else {
            $result[$key] = convertToArray(substr($string, ($pos+1)));
    
            return $result;
        }
    }
    
    var_dump(convertToArray('a.b.c.d'));
    

    Will ouput:

    array(1) {
      ["a"]=>
      array(1) {
        ["b"]=>
        array(1) {
          ["c"]=>
          array(1) {
            ["d"]=>
            array(0) {
            }
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题