PHP/SQL 分组

我有这样的问题,我只想对所有车型进行分组和列出一次,我的问题如下所示:

https://img1.sycdn.imooc.com/6544a1fb0001f14e11400213.jpg

我希望它看起来像这样:

https://img1.sycdn.imooc.com/6544a2030001840404150269.jpg

MySQL:


$all_model = $mysqli->query("SELECT mark, mark_url, model, model_url, engine, engine_url, generation, generation_url, year_production, body_car, body_car_url FROM auta WHERE mark_url = '$code_curr[3]' and model_url = '$code_curr[4]' GROUP BY generation, body_car");

PHP:


<?php foreach ($all_model as $value): ?>

    <div class="col-lg-3">

        <div class="crand-car-container">

            <?php echo "Generation:" . $value["generation"]; ?>

            <a href="/<?php echo $value['mark_url'] ?>/<?php echo $value['model_url'] ?>/<?php echo $value['generation_url'] ?>/<?php echo $value['body_car_url'] ?>"><?php echo $value['mark'] . " " . $value['model'] . " " . $value['year_production'] . " [" . $value['generation'] . "]" ?></a>

        </div>

    </div>

<?php endforeach; ?>


慕尼黑的夜晚无繁华
浏览 85回答 1
1回答

慕尼黑5688855

你绝对应该为你的项目使用一些模板引擎,因为随着时间的推移它会变得更加复杂,并且混合 PHP 和 HTML 会造成更大的混乱。我的想法是根据需要获取数据结构,然后迭代两个数组。使用模板引擎,它看起来会比我的代码更漂亮。<?php$generations = [];foreach ($all_model as $value) {&nbsp; &nbsp; if (!isset($generations[$value['generation']])) {&nbsp; &nbsp; &nbsp; &nbsp; $generations[$value['generation']] = [];&nbsp; &nbsp; }&nbsp; &nbsp; $generations[$value['generation']][] = $value;}foreach ($generations as $generation => $model): ?>&nbsp; &nbsp; <div class="col-lg-3">&nbsp; &nbsp; &nbsp; &nbsp; <div class="crand-car-container">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php echo "Generation:" . $generation; ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php foreach ($model as $value): ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href="/<?php echo $value['mark_url'] ?>/<?php echo $value['model_url'] ?>/<?php echo $value['generation_url'] ?>/<?php echo $value['body_car_url'] ?>"><?php echo $value['mark'] . " " . $value['model'] . " " . $value['year_production'] . " [" . $value['generation'] . "]" ?></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php endforeach; ?>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div><?php endforeach; ?>
打开App,查看更多内容
随时随地看视频慕课网APP