How to recursively create a multidimensional array?

前端 未结 5 1753
无人及你
无人及你 2020-12-17 06:47

I am trying to create a multi-dimensional array whose parts are determined by a string. I\'m using . as the delimiter, and each part (except for the last) shoul

5条回答
  •  一生所求
    2020-12-17 07:33

    // The attribute to the right of the equals sign
    $rightOfEquals = true; 
    
    $leftOfEquals = "config.debug.router.strictMode";
    
    // Array of identifiers
    $identifiers = explode(".", $leftOfEquals);
    
    // How many 'identifiers' we have
    $numIdentifiers = count($identifiers);
    
    
    // Iterate through each identifier backwards
    // We do this backwards because we want the "innermost" array element
    // to be defined first.
    for ($i = ($numIdentifiers - 1); $i  >=0; $i--)
    {
    
       // If we are looking at the "last" identifier, then we know what its
       // value is. It is the thing directly to the right of the equals sign.
       if ($i == ($numIdentifiers - 1)) 
       {   
          $a = array($identifiers[$i] => $rightOfEquals);
       }   
       // Otherwise, we recursively append our new attribute to the beginning of the array.
       else
       {   
          $a = array($identifiers[$i] => $a);
       }   
    
    }
    
    print_r($a);
    

提交回复
热议问题