开发者

how to set dynamic arrray names in php

hi i am trying to use dynamic array name . but when i run this code i get the error $marker is undefined .

 if (isset($arr)) {
               foreach ($arr as $key => $value) {

                  $marker.$key = a开发者_JS百科rray();

                   $marker.$key ['position'] = $value['lat'] . ',' . $value['long'];
                   $marker.$key ['draggable'] = 'TRUE';
                   $marker.$key ['ondragend'] = "test(this.getPosition().lat(),this.getPosition().lng())";

                   $this->ci->googlemaps->add_marker($marker.$key);
                   $i++;
                  }

           }

how can i create dynamic array name ????


Read The Fine Manual. The dot operator in PHP is completely unrelated to the dot operator in Javascript and similar languages - it does string concatenation. I don't quite understand what it is you're trying to do, but I'm fairly sure string concatenation is not it.

To clarify, what this does:

$marker.$key ['draggable'] = 'TRUE';

...is this;

  • get the value in $marker, interpret it as a string
  • get the value in $key, interpret it as a string
  • concatenate $marker and $string
  • interpret the resulting string as an array, and set the element at 'draggable' to the string (!) 'TRUE'. I'm not even sure what this does - string do allow for array-style indexing (which references individual characters), but I have no idea what non-integer indexes would yield.


Try this, when you do your concatenation PHP sees only $key to be an array, and concatenates the wrong way. Anyway, where is $marker defined??

if (isset($arr)) {
               foreach ($arr as $key => $value) {
                  $myarray = $marker.$key;
                  $myarray = array();

                   $myarray['position'] = $value['lat'] . ',' . $value['long'];
                   $myarray['draggable'] = 'TRUE';
                   $myarray['ondragend'] = "test(this.getPosition().lat(),this.getPosition().lng())";

                   $this->ci->googlemaps->add_marker($myarray);
                   $i++;
                  }
           }


Dynamic array names in Php can be done like this

foreach($arr as $key => $value) {
$myarray[$key] = $value;
}

Yet, you can also do like this, to set the array-variable

foreach($arr as $key => $value) {
${$key}[$key] = $value;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜