1 回答
TA贡献2036条经验 获得超8个赞
您需要做的第一件事是根据您可以使用的制造商对数组进行排序usort
,按值对没有制造商的条目进行排序id
。然后你可以遍历汽车,检查制造商是否与前一辆汽车相同,如果是,则输出一个新<div>
元素并关闭前一个(如果需要):
// sort based on manufacturer
usort($cars, function ($a, $b) {
if (!$a->manufacturer) {
// if both null, sort by id
if (!$b->manufacturer) return $a->id - $b->id;
// otherwise sort null values last
return 1;
}
if (!$b->manufacturer)
// sort null values last
return -1;
return $a->manufacturer - $b->manufacturer;
});
$lastmfg = 0;
foreach ($cars as $car) {
if (!$car->manufacturer || $car->manufacturer != $lastmfg) {
if ($lastmfg !== 0) echo "</div>\n";
echo '<div class="container'. ($car->manufacturer ? ' id' . $car->manufacturer : '') .'">'. "\n";
}
echo 'ID: ' . $car->id . ' - ' . $car->title . "\n";
$lastmfg = $car->manufacturer;
}
echo "</div>\n";
输出(用于扩展演示):
<div class="container id1">
ID: 1 - Golf
ID: 4 - Passat
ID: 5 - Toureg
</div>
<div class="container id2">
ID: 2 - Focus
ID: 6 - Galaxy
</div>
<div class="container id3">
ID: 9 - Phoenix
</div>
<div class="container">
ID: 3 - Jazz
</div>
<div class="container">
ID: 7 - Falcon
</div>
<div class="container">
ID: 8 - Commodore
</div>
<div class="container">
ID: 10 - Cressida
</div>
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报