1

I have a string like "create:this:assoc:array"

I want to create from this string

$array["create"]["this"]["assoc"]["array"] = "data"

what i have is

static public function add($data_path, $data) 
{
    if(!empty($data) && !empty($data_path)) {
        $keys = explode(":", $data_path);
        $looper = array();
        $length = count($keys) - 1;
        for ($i=0; $i <= $length ; $i++) 
        {
            if($i == $length)
                @$looper[$keys[$i]] = $data;
            else
            {

                @$looper[$keys[$i]] = $keys[$i+1];
            }
        }// end for loop
                echo '<pre>';
                print_r($looper);
                echo '</pre>';
    }
}

1 Answer 1

4

try something like this

 $s = "create:this:assoc:array";
 $array = array_reverse(explode(":", $s));
 $result = "data";
 foreach($array as $key => $value){
      $result = array($value => $result);
 }
 print_r($result);
Sign up to request clarification or add additional context in comments.

4 Comments

looks better than my! :) but you need to place $data at the end of the tree
not yet, now it's [0] => "data", should be $result = "data"; will be Array ( [create] => Array ( [this] => Array ( [assoc] => Array ( [array] => data ) ) ) )
and $result = array("data"); has to be $result = $data; because it will add an array to the end.
this is a full working one thnx to qwertmax static public function add($data_path, $data) { if(!empty($data) && !empty($data_path)) { $array = array_reverse(explode(":", $data_path)); $result = $data; foreach($array as $key => $value){ $result = array($value => $result); } } }

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.