开发者

Create dynamically named variables based on array keys

开发者 https://www.devze.com 2023-03-24 14:00 出处:网络
I have a multidimensional array and I want to create new variables based on the keys. I have written this code, but it returns NULL:

I have a multidimensional array and I want to create new variables based on the keys.

I have written this code, but it returns NULL:

$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
    if(is_array($value)){
        $i = 0;
        foreach($value as $v){
            $i++;
            $$key[$i] = $v;
        }
    }
}
var_开发者_如何学Godump($test);
?>

Where is the problem?


Make that:

${$key}[$i] = $v;
  • $$key[$i] means "the variable whose name is $key[$i]".
  • ${$key}[$i] means "position $i from the variable whose name is $key".

Also, it would be nice if you could initialize that $test array, so you won't get notices. Add the following before the second foreach:

$$key = array();


+1 to @Radu's answer, but you should also think about if these solutions would work for you:

$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
    if(is_array($value)){
      $$key = array_values($value);
    }
}
var_dump($test);

Or:

$a = array("test" => array("a", "b", "c"));
extract($a);
var_dump($test);

See: array_values(), extract().


$$key[$i] tries to get the variable whose name matches the value of $key[$i]. You could get a reference to $$key first, and then add an item to that reference:

$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
    if(is_array($value)){
        $i = 0;
        foreach($value as $v){
            $i++;
            $x = & $$key;
            $x[$i] = $v;
        }
    }
}
var_dump($test);
?>

[edit]

But I see, I'm somewhat slow in testing and writing an answer, since another good answer has been posted minutes ago. Still keeping this, since it uses a different and not much more complex approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消