1

我有一个应用程序,我可以在 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. 我怎样才能修复我的代码?谢谢!!

4

3 回答 3

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);
于 2013-02-26T08:46:11.917 回答
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}";
   }
}
于 2013-02-26T08:49:49.650 回答
0

foreach($openHrs as &$temp)

您不能在循环中使用 $temp 变量!

于 2013-02-26T08:48:17.063 回答