0

我的目标:创建动态变量,例如

$counterMon00 = 0;
$counterMon01 = 0;
$counterThu23 = 0;

到目前为止我的代码:

$array_days = ["Mon","Tue","Wed","Thu","Fri"];
for ($i = 0; $i < sizeof($array_days); $i++)
{
   $weekDay = (String) $array_days[$i];
   for($ii = 7; $ii < 10; $ii++)
   {
   "counter".${$weekDay}.${$ii} = 0;
   }
}

你能帮我解决这个问题吗

"counter".${$weekDay}.${$ii} = 0;

我尝试了不同的解决方案,但没有任何效果......

4

7 回答 7

1
$array_days = array("Mon","Tue","Wed","Thu","Fri");
for ($i = 0; $i < count($array_days); $i++)
{
   $weekDay = (String) $array_days[$i];
   for($ii = 7; $ii < 10; $ii++)
   {
   $var="counter".$weekDay.$ii;
   $$var;
   }

}
于 2013-07-31T09:10:49.140 回答
1

在使用它之前,您需要将变量设置为单个字符串。

$var = "counter".$weekDay.$ii;
$$var = 0;
于 2013-07-31T09:02:41.967 回答
1
${"counter".$weekDay.$ii} = 0;
于 2013-07-31T09:03:15.630 回答
1

尝试使用变量变量

$varName = "counter".${$weekDay}.${$ii};
$$varName = 0;//Note the $$

您可能还想研究构建一个数组而不是上面的,因为这会更容易(至少在我看来)。类似于将工作日映射到计数的数组,即

$arr["Mon"][3] = 0;
于 2013-07-31T09:06:33.543 回答
0

请尝试以下您在数组声明中也犯了错误

<?php
$array_days = array("Mon","Tue","Wed","Thu","Fri");
for ($i = 0; $i < sizeof($array_days); $i++)
{
  $weekDay = (String) $array_days[$i];
   for($ii = 7; $ii < 10; $ii++)
   {
    $var = "counter".$weekDay.(String)$ii;
    $$var = 0;
   }
}
?>
于 2013-07-31T09:11:54.040 回答
0

你想要一个数组!这正是他们的目的。在 99% 的情况下,变量变量都是一个坏主意。

$counter = [];
$days    = ["Mon","Tue","Wed","Thu","Fri"];

foreach ($days as $day) {
    foreach (range(7, 9) as $i) {
        $counter[$day][$i] = 0;
    }
}
于 2013-07-31T09:08:19.987 回答
0

尝试这个

$array_days = ["Mon","Tue","Wed","Thu","Fri"];
for ($i = 0; $i < sizeof($array_days); $i++)
{

//   $weekDay = $array_days[$i];
    for($ii = 0; $ii < 5; $ii++)
    {
    //echo "counter".${$weekDay}.${$ii} = 0;
        $a = "counter".$array_days[$i].$i.$ii;
        $$a = 0;
    }
}
于 2013-07-31T09:14:38.987 回答