Sorting a multidimensional array by value is fairly easy and has been answered multiple times already here
usort($myArray, function($a, $b) {
return $a['field'] - $b['field'];
});
The problem I am having now, is that I need another condition. Let's imagine I have an array with 10 cars and 10 motorcycles. These cars and motorcycles are each an array/object with values containing a field speed
. Like
$car1 = [
'speed' => 100,
'type' => 'car'
]
$car2 = [
'speed' => 120,
'type' => 'car'
]
$car3 = [
'speed' => 180,
'type' => 'car'
]
$motorcycle1 = [
'speed' => 80,
'type' => 'motorcycle'
]
Those are all stored in one array
$vechicles = [$car1, $car2, $car3, $motorcycle1]
What I now want to do is to sort by speed. Which is, as I said, easy
usort($myArray, function($a, $b) {
return $a['speed'] - $b['speed'];
});
The problem I am facing now, is, that independent of the speed value, at least every third vehicle MUST be a motorcycle. It can be, that the first entries are motorcycles, doesn't matter, but it can't be all cars. It always have to be at least one motorcycle. Doesn't matter here if it's 1, 2 or 3 motorcycles. So in the end it should look like this
$finalArray = [$car3, $car2, $motorcycle1, $car1];
As you can see, while $car1
is faster than $motorcycle1
, the motorcycle comes earlier.
The thing is, when I have two different arrays
$cars = [$car1, $car2, $car3]
and
$motorcycles = [$motorcycle1]
I can simply splice it in, like
array_splice($cars, 2, 0, $motorcycles[0]);
But then I got the problem that I can't sort it by speed. Is there a way to achieve this?