好的,在我开始之前,我想为这个问题道歉,写这个并且有意义是很难的,我花了3天时间寻找答案。
我有一个由12个项目组成的数组,这个月的所有日期都称为months_array
稍后在代码中我有一个foreach循环设置为另一个数组中的每个项目运行current_date
。此数组中的项目内容按顺序为01
到12
。
我会编写一些能够做我想做的但不理想的代码:
if ($current_date == "01") {
$January++;
}
我不会每个月都有一个,所以02和2月等。
我想要做的是取而代之的是让PHP弄清楚我们所指的月份,并将其视为字符串的名称,例如:[$moths_array[$current_date - 1]]++;
该代码不起作用。所以为了解释一下,months_array
中有月份名称。因此$months_array[0]
等于January
。如果$current_date = 1
比$months_array[$current_date - 1]
也等于1月。
所以我需要它而不是“1月”或“2月”等。并将其用作变量名称。那么无论什么月份,它都会加1。我可以使用echo $january
或echo $febuary
。
我希望这是有道理的,先谢谢。
我的代码:
//Print Analytics
echo "<div class='project_page_analytics'>";
echo "<div class='project_page_analytics_title'>";
echo "<p>";
echo "Analytics";
echo "</p>";
echo "</div>";
//Echo the Structure
$sql = "SELECT * FROM analytics_data WHERE corrospond='$project_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//If project
while($analytic = $result->fetch_assoc()) {
$analytics_array_date_temp_one = explode(" ", $analytic["date"]);
$date = $date . " " .$analytics_array_date_temp_one[1];
}
$analytic_array_date = explode(" ", $date);
$current_date = "01";
$months_array = array("January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$previous_date = $analytic_array_date[0];
$March = 0;
foreach($analytic_array_date as &$current_date) {
if ($previous_date == $current_date) {
[$months_array[$current_date - 1]] + 1;
}
}
echo $March;
}
答案 0 :(得分:0)
我没有碰到你的代码。我认为这将解决您的问题。
<?php
$current_date = array("1","1","3","2");
$months_array = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
foreach($months_array as $month){
${$month} = 0;
}
for($i=0;$i<count($current_date);++$i) {
$date = $current_date[$i];
${$months_array[$date-1]}++;
}
echo $January;
echo $February;
?>