从字符串创建数组

时间:2010-09-25 10:41:27

标签: php arrays associative-array

我需要像这样创建数组:

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

由此:

firstkey.secondkey.nkey.(...)

3 个答案:

答案 0 :(得分:12)

$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

答案 1 :(得分:1)

我对此的看法:

<?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()

您希望最深层钥匙的价值是什么?

答案 2 :(得分:0)

尝试类似:

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