【问题标题】:Creating array from string从字符串创建数组
【发布时间】:2010-09-25 10:41:27
【问题描述】:

我需要像这样创建数组:

Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))

从这里:

firstkey.secondkey.nkey.(...)

【问题讨论】:

  • 这听起来你将不得不写一些递归的东西......
  • 你从哪里得到这样的字符串?
  • 最深的条目是空数组还是字符串?

标签: php arrays associative-array


【解决方案1】:
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
   // add an empty array to the current array
   $current[ $key ] = array();
   // descend into the new array
   $current = &$current[ $key ];
}
//$result contains the array you want

【讨论】:

    【解决方案2】:

    我对此的看法:

    <?php
    
    $theString = "var1.var2.var3.var4";
    $theArray = explode(".", $theString); // explode the string into an array, split by "." 
    $result =  array();
    $current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
    
    while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
        $current[$key] = array(); // add the new key => value pair
        $current = &$current[$key]; // set the reference point to the newly created array.
    }
    
    var_dump($result);
    
    ?>
    

    在 while 循环中使用 array_push()

    您希望最深键的值是多少?

    【讨论】:

      【解决方案3】:

      尝试类似:

      function dotToArray() {
        $result = array();
        $keys = explode(".", $str);
        while (count($keys) > 0) {
          $current = array_pop($keys);
          $result = array($current=>$result);
        }
        return $result;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-10
        • 1970-01-01
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        • 1970-01-01
        • 2016-01-24
        相关资源
        最近更新 更多