我有一个应用程序,我在MySql上保存工作日和营业时间如下:
0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22
php数组以以下格式从Mysql获取
Array ( [open_hours] => 0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22 )
0 10 22
表示Monday 10am 22pm
我目前的代码似乎不太好,下面是我用来格式化日期和时间的代码
$openHrs = $businessMapper->getBusinessHours($business_id);
// return Array ( [open_hours] => 0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22 )
$openHrs = explode(",", $openHrs['open_hours']);
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
foreach($openHrs as &$temp) {
//$temp = $weekdays[$temp[0]]
$temp = explode(" ", $temp);
//$temp = explode(" ", $temp);
$temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
$temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';
$temp = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
}
但问题是,我只得到一个结果,这是Sat 10am 10pm
。我如何修复我的代码?谢谢! !
问题:每次foreach迭代时,它都会重写前一个值,即$temp
将只包含最后一个值。
解决方案:添加一个变量$res作为数组,并将每个值赋给它。
Try this:
$openHrs = $businessMapper->getBusinessHours($business_id);
// return Array ( [open_hours] => 0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22 )
$openHrs = explode(",", $openHrs['open_hours']);
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
$res = array();
foreach($openHrs as &$temp) {
//$temp = $weekdays[$temp[0]]
$temp = explode(" ", $temp);
//$temp = explode(" ", $temp);
$temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
$temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';
$res[] = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
}
echo "<pre>";
print_r($res);
foreach($openHrs as &$temp)
你不能在循环中使用$temp变量!
$openHrs = $businessMapper->getBusinessHours($business_id);
$openHrs = explode(",", $openHrs['open_hours']);
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
$resultArray = array();
foreach($openHrs as $temp) {
$tempRecord = explode(" ", $temp);
if (count($tempRecord) == 3) {
$timeBegin = $tempRecord[1] > 12 ? $tempRecord[1] - 12. 'pm' : $tempRecord[1]. 'am';
$timeEnd = $tempRecord [2] > 12 ? $tempRecord[2] - 12. 'pm' : $tempRecord[2]. 'am';
$resultArray[] = "{$weekdays[$temp[0]]} {$timeBegin} {$timeEnd}";
}
}