Sorting a multidimensional array by value with a condition

Sorting a multidimensional array by value is pretty simple and has already been answered several times

usort($myArray, function($a, $b) {
    return $a['field'] - $b['field'];
});

      

The problem I am facing now is that I need a different condition. Imagine I have an array with 10 cars and 10 motorcycles. These cars and bikes are an array / object with values ​​containing a field speed

. how

$car1 = [
    'speed' => 100,
    'type' => 'car'
]
$car2 = [
    'speed' => 120,
    'type' => 'car'
]
$car3 = [
    'speed' => 180,
    'type' => 'car'
]
$motorcycle1 = [
    'speed' => 80,
    'type' => 'motorcycle'
]

      

They are all stored in one array

$vechicles = [$car1, $car2, $car3, $motorcycle1]

      

Now I want to sort by speed. Which, as I said, is easy

usort($myArray, function($a, $b) {
        return $a['speed'] - $b['speed'];
});

      

The problem I'm facing right now is that regardless of the speed setting, at least every third car MUST be a motorcycle. Maybe the first entries are motorcycles, it doesn't matter, but these are not all cars. There must always be at least one motorcycle. It doesn't matter if it's 1, 2 or 3 bikes. So at the end it should look like this.

$finalArray = [$car3, $car2, $motorcycle1, $car1];

      

As you can see, while $car1

faster than $motorcycle1

, the bike goes earlier.

The point is that I have two different arrays

$cars = [$car1, $car2, $car3]

      

and

$motorcycles = [$motorcycle1]

      

I can just insert it 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?

+3


source to share


1 answer


Ok, the simplest solution

$vehicles = [...]; // sorted by speed already

$count = count($vehicles);
$temp = 0;

foreach($vehicles as $key => $veh){

    if(is_car($veh)){
        $temp++;
    }else{
        $temp = 0;
    }

    if($temp == 3){

        for($i = $key + 1; $i<=$count; $i++){

            if(is_motorcycle($vehicles[$i])){

                array_splice($vehicles, $key, 0, $vehicles[$i]);
                break;

            }

        }
        $temp = 0;

    }

}

      



Obviously this is not working code, I just wrote it to illustrate my idea, if you think you can benefit from it, happy setup!: P

+1


source







All Articles