我的目标:创建像
这样的动态变量$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;
我尝试了不同的解决方案,但没有任何效果......
答案 0 :(得分:1)
在使用之前,您需要将变量设置为单个字符串。
$var = "counter".$weekDay.$ii;
$$var = 0;
答案 1 :(得分:1)
${"counter".$weekDay.$ii} = 0;
答案 2 :(得分:1)
尝试使用variable variables:
$varName = "counter".${$weekDay}.${$ii};
$$varName = 0;//Note the $$
你也可能想要建立一个数组而不是上面的数据,因为这会更容易(至少在我看来)。类似于工作日的数组映射计数,即
$arr["Mon"][3] = 0;
答案 3 :(得分: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;
}
}
答案 4 :(得分:0)
你想要一个数组!这正是他们的目的所在。在99%的情况下,变量变量都是个坏主意。
$counter = [];
$days = ["Mon","Tue","Wed","Thu","Fri"];
foreach ($days as $day) {
foreach (range(7, 9) as $i) {
$counter[$day][$i] = 0;
}
}
答案 5 :(得分: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;
}
}
?>
答案 6 :(得分: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;
}
}