我有一个应用程序,我在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
的结果。我该如何修复我的代码?谢谢!
答案 0 :(得分:1)
问题:每次foreach迭代时都会写入前一个值,即$temp
将只包含最后一个值。
解决方案:添加了一个变量$ res作为数组并为其分配了每个值。
试试这个:
$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);
答案 1 :(得分:0)
foreach($ openHrs as&amp; $ temp)
你不能在循环中使用$ temp变量!
答案 2 :(得分:0)
$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}";
}
}