到目前为止,我一直在 foreach 循环中运行 MySQL 查询,但现在意识到先运行查询然后遍历数组更有效。我想知道我是否可以进一步优化下面的代码——它使用 3 个表中的数据来构建谷歌图表。例如,是否可以在 foreach 循环中添加 where 子句,这样我就不需要在每个循环中包含 if 子句?
$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);
}