簡體   English   中英

循環遍歷mysqli結果數組以獲取所有信息

[英]Loop through mysqli results array once to get all information

我正在查詢數據庫中的數據,但是為了執行所需的操作,我最終至少遍歷了該結果數組三遍。 我如何從陣列中獲取所需的所有信息而不必循環那么多次? 我需要根據先前循環的結果從數組中獲取數據。 下面的代碼是我只想查詢一次數據庫的唯一方法。

$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>';
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM