dongxi7704 2015-04-30 14:49
浏览 39
已采纳

使用条件按值对多维数组进行排序

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?

  • 写回答

1条回答 默认 最新

  • drnysdnnb2909701 2015-04-30 15:00
    关注

    Well, easiest 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 tweaking! :P

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题