<?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";
preferences:
24.67 ms | 404 KiB | 5 Q