Php 仅当值相同时,foreach循环内的值求和
我必须检查条件,即用户在时间表中输入的时间不得超过24小时/天。例如(yyyy-mm-dd)2014-12-21 | 5小时,2014-12-21 | 10小时,2014-12-21 | 10小时然后点击提交按钮,我需要汇总当天的小时数,并提醒用户“每天输入的小时数不得超过24小时” 这是我的密码Php 仅当值相同时,foreach循环内的值求和,php,html,Php,Html,我必须检查条件,即用户在时间表中输入的时间不得超过24小时/天。例如(yyyy-mm-dd)2014-12-21 | 5小时,2014-12-21 | 10小时,2014-12-21 | 10小时然后点击提交按钮,我需要汇总当天的小时数,并提醒用户“每天输入的小时数不得超过24小时” 这是我的密码 <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.mi
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form name="" action="#" method="post">
<?php for ($i=0; $i<5; $i++){ ?>
<label>date</label>
<input class="datefield" id="datefiled_<?php echo $i; ?>" type="date" name="datevalue[]" value="" / >
<label>hrs</label>
<input class="hrscheck" id="hrscheck_<?php echo $i; ?>" type="number" value="" name="hrs[]" />
<br />
<?php } ?>
<input type="submit" name="submit" value="save">
</form>
<?php
if(isset($_POST['submit']))
{
$datevalue = $_POST['datevalue'];
$prevDate = '';
$hrs=0;
foreach($datevalue as $key=>$values)
{
echo $curDate = ($values);
echo "=>";
echo $hrs = $_POST['hrs'][$key];
echo "<br>";
if ($curDate == $prevDate) {
echo $hrs +=$hrs;
}
$prevDate = $curDate;
}
}
?>
</body>
</html>
我必须将2014-12-25的三个小时值(10+10+10)=30相加,并提醒用户(不应超过24小时)您可以构建一个摘要数组,然后过滤当天报告超过30小时的内容:
// build summary array: [date] => array of time values
$summary = [];
foreach($datevalue as $key=>$values) {
$summary[$values][] = $_POST['hrs'][$key];
}
// filter them
if (array_filter($summary, function($item) {
return array_sum($item) > 24;
})) {
echo "UH OH, a day doesn't have more than 24 hours";
}
// build summary array: [date] => array of time values
$summary = [];
foreach($datevalue as $key=>$values) {
$summary[$values][] = $_POST['hrs'][$key];
}
// filter them
if (array_filter($summary, function($item) {
return array_sum($item) > 24;
})) {
echo "UH OH, a day doesn't have more than 24 hours";
}