0

The string

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

should create an array like

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

I managed to come up with this:

function create_array(&$arr, $string, $data){


  $parts = explode('.', $string);
  $key = array_shift($parts); // first key

  $new_arr = array();
  $have_empty_slot = false;

  if(!isset($arr[$key])){
    $arr[$key] = array();
    $have_empty_slot = true;
  }

  $new_arr = &$arr[$key];

  foreach($parts as $part){
    if(!isset($new_arr[$part])){
      $new_arr[$part] = array();
      $have_empty_slot = true;
    }

    $new_arr = &$new_arr[$part];
  }

  // last one
  if($have_empty_slot)
    $new_arr = $data;

}    


$arr = array('a' => array('aa' => array('aaa' => 555)), 'b' => 55);

create_array($arr, 'c.cc.dd', 4545); // <-- works

create_array($arr, 'a.aa.aa2', 33); // <-- works

create_array($arr, 'a.aa.aaa.aaaaaaa', 4545); // <-- connection closed by remote server lol



print_r($arr);

So if I try to add a new element after the last element of an existing set of elements I get that connection closed by remote server error. What's wrong with it?

2
  • 1
    What is $arr and what is that number (3rd parameter)? Commented Feb 5, 2012 at 0:33
  • the 3rd parameter is not important, that's the value of the last child element Commented Feb 5, 2012 at 0:34

2 Answers 2

1

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

Comments

1

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) {
        }
      }
    }
  }
}

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.