我正在查询数据库中的数据,但是为了完成我所需要的操作,我至少要循环遍历结果数组三次。如何在不循环这么多次的情况下从数组中获取所有需要的信息?我需要根据之前循环的结果从数组中获取数据。下面的代码是我能想出的唯一方法,以便只查询数据库一次。
$recordSQL = mysqli_query($link, $sqlString);
$resultMonths = array();
while($recordResult = mysqli_fetch_assoc($recordSQL)) $resultMonths[] = $recordResult['date'];
mysqli_data_seek($recordSQL, 0);
$uniqueMonths = array_unique($resultMonths);
foreach($uniqueMonths as $key => $date){
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
$resultCompanies = array();
while($companyResult = mysqli_fetch_assoc($recordSQL)){
if($companyResult['date'] == $date) $resultCompanies[] = $companyResult['company'];
}
mysqli_data_seek($recordSQL, 0);
$uniqueCompanies = array_unique($resultCompanies);
$oldco = '';
foreach($uniqueCompanies as $key => $company){
$x = 0;
while($typeResult = mysqli_fetch_assoc($recordSQL)){
if($typeResult['date'] == $date && $typeResult['company'] == $company){
if($oldco != $typeResult['company']){
if($x != 0) echo '</div>';
echo '<div class="company-record">'.$typeResult['name'].' - ';
}
if($x > 0) echo ', ';
echo translateID('Type', $typeResult['type']).'('.translateID('Section', $typeResult['section']).')';
$oldco = $typeResult['company'];
$x++;
}
}
echo '</div>';
mysqli_data_seek($recordSQL, 0);
}
}
仅供参考,你实际上是循环N**3次。这样做:
$month_company_rows = array();
while ($row = mysqli_fetch_assoc($recordSQL)) {
$month_company_rows[$row['date']][$row['company']][] = $row;
}
foreach ($month_company_rows as $date => $company_rows) {
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
foreach ($company_rows as $company => $rows) {
echo '<div class="company-record">'.$company.' - ';
foreach ($rows as $x => $row) {
if($x > 0) echo ', ';
echo translateID('Type', $row['type']).'('.translateID('Section', $row['section']).')';
}
echo '</div>';
}
}