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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作