简体   繁体   English

如何根据两个键值对数组键进行排序?

[英]How to sort array key based on two key values?

Let's say I need to run a for loop through an array where I need to check against to key value. 假设我需要在数组中运行一个for循环,在该循环中需要检查键值。 I would like to print the array element that doesn't match BEFORE the element that doesn't match. 我想在不匹配的元素之前打印不匹配的数组元素。

So using the array from below (extra values added for clarity), I would like it to print as follows. 因此,使用下面的数组(为清楚起见添加了额外的值),我希望它按以下方式打印。 It needs to match the current_tag and last_tag values. 它需要匹配current_taglast_tag值。 If they don't match, that key needs to be printed prior to the others. 如果它们不匹配,则需要先打印该密钥。

Desired results 所需结果

TEST2

TEST1 
TEST3 
TEST4 

Array 数组

array(2) {
    [0]=>
    array(3) {
        ["name"]=>
            string(3) "TEST1"
        ["current_tag"]=>
            string(13) "20121129_TEST1"
        ["last_tag"]=>
            string(13) "20121129_TEST1"
    }
    [1]=>
    array(3) {
        ["name"]=>
            string(3) "TEST2"
        ["current_tag"]=>
            string(13) "20121205_TEST2"
        ["last_tag"]=>
            string(13) "20121129_TEST2"
    }
    ...
    ...
    ...
    ...
}

I would usort the array with a custom callback to sort the array. 我会usort阵列与一个自定义的回调对数组进行排序。 After sorting you can just print every name key. 排序后,您可以只打印每个name键。

usort($array, function($a, $b) {
    $match_a = $a['current_tag'] == $a['last_tag'];
    $match_b = $b['current_tag'] == $b['last_tag'];

    if ($match_a && $match_b) {
        return 0;
    } elseif ($match_a && !$match_b) {
        return 1;
    } elseif (!$match_a && $match_b) {
        return -1;
    }
});

array_walk($array, function($item) {
    echo $item['name'];
});

If it is ordered in the wrong order just switch the 1 and -1 return values. 如果顺序错误,只需切换1和-1返回值即可。

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

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