排序多维数组由值和条件 [英] Sort multidimensional array by value with a condition

查看:117
本文介绍了排序多维数组由值和条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

排序按值多维数组是相当容易的,并已已经在这里回答了多次

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'];
});

我现在遇到的问题是,我需要的其他条件。让我们想象一下我有10辆汽车和摩托车10辆的数组。这些汽车和摩托车都包含一个字段速度值每一个数组/对象。像

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'];
});

我现在面临的问题是,这依赖于速度值,至少每三车必须是一辆摩托车。它可以是,第一项是摩托车,不要紧,但不能全是车。它总是必须至少有一个摩托车。如果是1,2或3摩托车在这里并不重要。
那么到底应该是这样的。

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];

正如你所看到的,而 $ CAR1 $ motorcycle1 更快,摩托车来早。

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]

$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?

推荐答案

好了,最简单的办法

$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;

    }

}

显然,这是行不通的code,我只是写它来说明我的想法,如果你认为你可以从中受益,快乐的调整! :P

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

这篇关于排序多维数组由值和条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆