简体   繁体   English

按2个自定义顺序对php数组进行排序

[英]Sorting php array by 2 custom order

What is the best way to sort a php array using 2 custom sequential ordering: 什么是使用2个自定义顺序对php数组进行排序的最佳方法:

$valueOrder = array('dev1', 'com', 'check', 'data');
$titleOrder = array('title4', 'title7', 'title3', 'title9');
$array = array(
    array('value' => 'com', 'title' => 'title7'),
    array('value' => 'dev1', 'title' => 'title9'),
    array('value' => 'dev1', 'title' => 'title7'),
    array('value' => 'data', 'title' => 'title4'),
);

I like this solution but it works only for one custome order : 我喜欢此解决方案,但仅适用于一个客户订单:

usort($array, function ($a, $b) use ($valueOrder) {
    $pos_a = array_search($a['value'], $valueOrder);
    $pos_b = array_search($b['value'], $valueOrder);
    return $pos_a - $pos_b;
});

var_dump($array);

it's possible to use the same solution using $valueOrder and $titleOrder ??? 可以使用$ valueOrder和$ titleOrder使用相同的解决方案?

In the user defined custom sort function, you compare the items by value and if that value is the same, then compare by label. 在用户定义的自定义排序功能中,您按值比较项目,如果该值相同,则按标签比较。 But, you should be aware that array_search returns FALSE in case the needle is not found so arithmetic operations will not distinguish FALSE from ZERO . 但是,您应该注意,如果array_search该指针, array_search将返回FALSE ,因此算术运算不会将FALSEZERO区分开。

usort($array, function ($a, $b) use ($valueOrder, $titleOrder) {
    $pos_a = search($a['value'], $valueOrder);
    $pos_b = search($b['value'], $valueOrder);

    if ($pos_a === $pos_b) {
        return search($a['title'], $titleOrder) - search($b['title'], $titleOrder);
    }
    return $pos_a - $pos_b;
});


//just like array_search but more friendly to comparison
function search($needle, $heystack)
{
    $pos = array_search($needle, $heystack);

    if (false === $pos) {
        return PHP_INT_MAX;
    }

    return $pos;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM