从字符串php创建动态关联数组

时间:2013-09-23 18:58:19

标签: php associative-array

我有一个像“create:this:assoc:array”

这样的字符串

我想从这个字符串中创建

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

我拥有的是

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 个答案:

答案 0 :(得分:4)

尝试这样的事情

 $s = "create:this:assoc:array";
 $array = array_reverse(explode(":", $s));
 $result = "data";
 foreach($array as $key => $value){
      $result = array($value => $result);
 }
 print_r($result);