2

I need to create array like that:

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

From this:

firstkey.secondkey.nkey.(...)
3
  • 1
    This sounds like you're going to have to write something recursive... Commented Sep 25, 2010 at 10:43
  • where do you get such a string? Commented Sep 25, 2010 at 10:51
  • Is the deepest entry an empty array, or a string? Commented Sep 25, 2010 at 14:52

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

My take on this:

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

?>

With an array_push() in the while loop.

What do you want the value of the deepest key to be?

Comments

0

Try something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.