直到現在,我一直在foreach循環中運行MySQL查詢,但現在認識到先運行查詢然後遍歷數組會更高效。我想知道是否可以優化下面的代碼 - 使用3個表中的數據構建Google圖表 - 進一步。是否有可能例如添加一個where子句到foreach循環,以便我不需要在每個循環中包含if子句?使用foreach循環優化迭代遍歷數組
$begin = new DateTime(date('Y-m-d', strtotime('-28 days')));
$end = new DateTime(date('Y-m-d', strtotime('+1 day')));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
$sessions = $wpdb->get_results($wpdb->prepare("SELECT Due,Date from patient_sessions WHERE Type='Session'"));
$work_times = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from work_times"));
$expenses = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from expenses WHERE Client='Psychotherapy'"));
foreach ($period as $dt) {
$session_total = 0;
$work_time_total = 0;
$expense_total = 0;
$date = $dt->format("Y-m-d");
$date_display = $dt->format("D j M");
foreach ($sessions as $session) {
if (substr($session->Date,0,10) === $date) {
$session_total = ($session_total+$session->Due);
}
}
foreach ($work_times as $work_time) {
if ($work_time->Date === $date) {
$work_time_total = ($work_time_total+$work_time->Amount);
}
}
foreach ($expenses as $expense) {
if ($expense->Date === $date) {
$expense_total = ($expense_total+$expense->Amount);
}
}
$balance = ($session_total + $work_time_total - $expense_total);
$temp = array();
$temp[] = array('v' => (string) $date_display);
$temp[] = array('v' => (string) $balance);
$rows[] = array('c' => $temp);
}
我不明白你的最後一行:'$ rows [] = array('c'= > $ temp);',你想在這裏做什麼? – Revent 2013-04-24 19:51:13