循环遍历 mysqli 结果数组一次获取所有信息

标签: MySQL PHP
发布时间: 2017/1/9 21:30:52
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我查询数据库中的数据,但为此我的需要我最终遍历结果数组至少三次。那怎么所有我需要的信息而不必这么多次循环数组中?我需要从基于从先前的循环结果的数组中获取数据。下面的代码是唯一的方法我可以计算出,只有一次查询数据库。

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

解决方法 1:

供你参考,你实际上循环 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>';
    }
}
赞助商