2013-02-26 127 views
1

我有一個應用程序,其中i上的MySQL保存平日和營業時間如下:PHP數組迭代失敗

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

你得到了什麼輸出_do_? – 2013-02-26 08:47:03

回答

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); 
0

的foreach

你不能在你的循環使用$臨時變量($ openHrs爲& $ TEMP)!

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}"; 
    } 
}