在循环中访问(索引)数组中的变量名称

时间:2014-09-11 20:33:03

标签: php arrays foreach

我正在编写一个使用foreach循环变量数组的PHP代码,我试图获取变量的名称以在javascript代码中使用它 这是我的代码

$arr = array($devices1, $devices2, $devices3, $devices4, $devices5, $devices6);
    foreach ($arr as $key => $value)
    {
        if($value == '1')
        {
            echo "
        <script type=\"text/javascript\">
        document.getElementById($key).checked = true;
        </script>
    ";
        }
    }

当我运行代码时,$ key取值0,1,2我需要的是取device1,devices2,devices3 ......所以变量的名称。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

好吧,你可以建立自己的名字(“设备”+($ key + 1))或使它成为一个关联数组(虽然没有多大意义):

$arr = array('devices1'=>$devices1,'devices2'=>$devices2,'devices3'=>$devices3);// etc...

然而,最有意义的是使用简单的字符串数组:

$arr = array('devices1', 'devices2', 'devices3', 'devices4', 'devices5', 'devices6');

然后在JS片段中使用$ value而不是$ key。


更新

以下是如何使用关联数组版本:

完整代码

$arr = array('devices1'=>$devices1,'devices2'=>$devices2,'devices3'=>$devices3);
foreach ($arr as $key => $value)
{
    if($value == '1') // $value will be the value of each array item
    {
        echo "
    <script type=\"text/javascript\">
    document.getElementById($key).checked = true; // and $key is the string key
    </script>                                     // like 'devices1', etc.
";
    }
}