2013-03-06 123 views
-1

我有一個代碼,我可以節省MySQL的特定業務的營業時間和工作日。當數據被取出從MySQL的輸出將是如下:PHP得到工作日時間

Array ([open_hours] => 0 10 0,1 10 0,2 10 0,3 10 0,4 10 0,5 10 0,6 10 0) 

0 10 0僅僅意味着Mon 10am 12am,如果是這樣的0 15 18意味着Mon 3pm 6pm。這不是因爲我已經通過下面的代碼解決了這個問題:

$openHrs = explode(",", $openHrs['open_hours']); 

     $weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'); 
     $res  = array(); 
     foreach($openHrs as &$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]; 
     } 

現在我怎麼可以編寫更先進,因此如果今天是星期一我只需要顯示週一的輸出結果? 0 10 0Mon 10am 12am?感謝您的幫助

+0

你在哪裏存儲上述代碼中的日期數值? – Sriniwas 2013-03-06 05:07:32

+0

@Sriniwas你是什麼意思? – d3bug3r 2013-03-06 05:16:11

+0

沒有..只是一個誤解.. :) – Sriniwas 2013-03-06 08:16:40

回答

1

如果您想在今天的工作日過濾出open_hours,則下面的代碼應該執行。

$openHrs = explode(",", $openHrs['open_hours']); 

    $weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'); 
    $res  = array(); 

    $todayWeekDay = date('D'); // get today's weekday 
    $todayWeekNum = array_search($todayWeekDay, $weekdays); // get number for today's weekday 

    foreach($openHrs as &$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'; 
     // only add the item where the weekday is equal to today's 
     if ($temp[0] == $todayWeekNum) { 
      $res[] = $weekdays[$temp[0]] . ' ' . $temp[1] . ' - ' . $temp[2]; 
     } 
    } 
2

U可以使用此代碼解決這個問題

 for($i=0;$i<=6;$i++) 
    { 
    if($res[$i]==date('w')) //get today's week number 
      { 
       echo $res[$i]." ".$temp[1]." ".$temp[2];    
      } 
    } 

OR

 for($i=0;$i<=6;$i++) 
    { 
    if($res[$i]==date('D')) // get today's weekday 
      { 
       echo $res[$i]." ".$temp[1]." ".$temp[2];    
      } 
    } 
0
$i; // the weekday; comes as input 

    $openHrs = explode(",", $openHrs['open_hours']); 

    $weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'); 
    $res  = array(); 
    $temp = explode(" ", $openHrs[$i]); 

    $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]; 
0

那麼它聽起來像一個棘手的問題,但看它是否值得嘗試這樣的:

$open_hours = array(Mon 10 0,Tue 10 0,Wed 10 0,Thu 10 0,Fri 10 0,Sat 10 0,Sun 10 0); 
$today = date('D'); 
$associate_array_key = array_keys($open_hours, $today); 
$openHrs = explode(" ", $open_hours[$associate_array_key]); 
foreach($openHrs as &$temp) { 
    $temp[0]; 
    $temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am'; 
    $temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am'; 
} 

這只是我能想到的概念,當然可能會有一些代碼需要操作!