[英]calculating no of days in given month
I have the LatestValuesDate 'Apr','May','Jun'
.I have array with no of days for the months.我有 LatestValuesDate 'Apr','May','Jun'
。我有几个月没有几天的数组。 If LatestValuesDate
is may I want to show the number of days =61
.如果LatestValuesDate
可能我想显示number of days =61
。 if LatestValuesDate
is Jul
I want to show the number of days =91
but now I got only 31
如果LatestValuesDate
是Jul
我想显示number of days =91
但现在我只有31
$month_days=array("Apr"=>"30", "May"=>"31", "Jun"=>"30", "Jul"=>"31", "Aug"=>"31", "Sep"=>"30", "Oct"=>"31", "Nov"=>"30", "Dec"=>"31", "Jan"=>"31", "Feb"=>"28", "Mar"=>"30");
$val='May';
$days1=0;
$noOfDays=$days1+$month_days[$val];
For your expected result, you would need to loop through the array and sum the values into a variable.对于您的预期结果,您需要遍历数组并将值相加到一个变量中。 But you will have to stop the loop after adding the value according to your $val variable.但是您必须在根据 $val 变量添加值后停止循环。 You can achieve that using the following code:您可以使用以下代码来实现:
$month_days=array("Apr"=>"30", "May"=>"31", "Jun"=>"30", "Jul"=>"31", "Aug"=>"31", "Sep"=>"30", "Oct"=>"31", "Nov"=>"30", "Dec"=>"31", "Jan"=>"31", "Feb"=>"28", "Mar"=>"30");
$noOfDays = 0;
$val='May';
foreach($month_days as $key=>$value){
$noOfDays = $noOfDays + $value;
if($key == $val)
break;
}
echo $noOfDays;
NOTE: March has the wrong number of days in your array declaration, it should be 31.注意:3 月在您的数组声明中的天数有误,它应该是 31。
I was always advised to not use break
like commands in loops and to always have a "well defined loop" that doesn't require a break
.我总是被建议不要在循环中使用类似break
的命令,并且总是有一个不需要break
的“定义明确的循环”。
This uses a while
loop and a flag.这使用了一个while
循环和一个标志。 If the search is not found, the loop will end summing all values.如果未找到搜索,则循环将结束对所有值求和。
$month_days = ['Apr'=>'30', 'May'=>'31', 'Jun'=>'30', 'Jul'=>'31', 'Aug'=>'31', 'Sep'=>'30', 'Oct'=>'31', 'Nov'=>'30', 'Dec'=>'31', 'Jan'=>'31', 'Feb'=>'28', 'Mar'=>'31'];
$val = 'May';
$day_count = 0;
$i = 0;
$keys = array_keys($month_days);
$done = 0;
while (!$done)
{
$done = $keys[$i] == $val || $i >= count($month_days) ? 1 : 0;
$day_count += $month_days[$keys[$i]];
$i++;
}
echo 'Day Count: ' . $day_count . "\n";
echo 'i: ' . $i . "\n";
Just if you don't want to use foreach()
:只是如果您不想使用foreach()
:
$month_days=array("Apr"=>"30", "May"=>"31", "Jun"=>"30", "Jul"=>"31", "Aug"=>"31", "Sep"=>"30", "Oct"=>"31", "Nov"=>"30", "Dec"=>"31", "Jan"=>"31", "Feb"=>"28", "Mar"=>"30");
$val='May';
$noOfDay = 0;
$month_index = array_search($val, array_keys($month_days));
$noOfDay = array_sum(array_slice($month_days,0,$month_index +1));
var_dump($noOfDay);
Output: int(61)
Output: int(61)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.