<?php
$cars = array (
0 =>
(object)(array(
'id' => 1,
'title' => 'Golf',
'manufacturer' => 1
)),
1 =>
(object)(array(
'id' => 2,
'title' => 'Focus',
'manufacturer' => 2
)),
2 =>
(object)(array(
'id' => 3,
'title' => 'Jazz',
'manufacturer' => null
)),
3 =>
(object)(array(
'id' => 4,
'title' => 'Passat',
'manufacturer' => 1
)),
4 =>
(object)(array(
'id' => 5,
'title' => 'Toureg',
'manufacturer' => 1
)),
5 =>
(object)(array(
'id' => 6,
'title' => 'Galaxy',
'manufacturer' => 2
)),
6 =>
(object)(array(
'id' => 7,
'title' => 'Falcon',
'manufacturer' => null
)),
7 =>
(object)(array(
'id' => 8,
'title' => 'Commodore',
'manufacturer' => null
)),
8 =>
(object)(array(
'id' => 9,
'title' => 'Phoenix',
'manufacturer' => 3
)),
9 =>
(object)(array(
'id' => 10,
'title' => 'Cressida',
'manufacturer' => null
))
);
// 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";
- Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
- <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>
preferences:
93.72 ms | 408 KiB | 5 Q