简体   繁体   English

按每个内部数组中的最后一个值对2D数组排序

[英]Sort 2D array by last value in each inner array

I have an array of arrays and all of the inner-arrays contain 4 strings and an int. 我有一个数组数组,所有内部数组都包含4个字符串和一个整数。

Right now, I am traveling through the arrays with a foreach and I am looking for help sorting the inner arrays by the number ( the last item ) so that the higher / larger ones are first and then transferring them into a new array that is sorted in that manner. 现在,我正在使用foreach数组,我正在寻求帮助,以数字对内部数组进行排序(最后一项),以便先将较大的/较大的数组先放入,然后再将它们转移到已排序的新数组中以这种方式。

$twoDUnsorted = array(
    array(
        0=>"the",
        1=>"quick",
        2=>"brown",
        3=>"fox",
        4=>650
    ),
    array(
        0=>"jumps",
        1=>"over",
        2=>"the",
        3=>"lazy",
        4=>420
    ),
    array(
        0=>"it",
        1="was",
        2=>"the",
        3=>"worst"
        4=>1016
    ),
    array(
        0=>"of",
        1=>"times",
        2=>"it",
        3=>"was",
        4=>768
    ),
    array(
        0=>"the",
        1=>"best",
        2=>"of",
        3=>"times,
        4=>123
   )
);

and then one travels through it with a for each, sorts it by the last item in each inner array, and then uses array_push to push the arrays into a new 2D array in order. 然后使用,每个进行遍历,按每个内部数组中的最后一项对它进行排序,然后使用array_push将数组按顺序推入新的2D数组。

So the new 2D array would look like: 因此,新的2D数组如下所示:

$twoDSorted = array(
    array(
        0=>"it",
        1="was",
        2=>"the",
        3=>"worst"
        4=>1016
    ),
    array(
        0=>"of",
        1=>"times",
        2=>"it",
        3=>"was",
        4=>768
    ),
    array(
        0=>"the",
        1=>"quick",
        2=>"brown",
        3=>"fox",
        4=>650
    ),
    array(
        0=>"jumps",
        1=>"over",
        2=>"the",
        3=>"lazy",
        4=>420
    ),
    array(
        0=>"the",
        1=>"best",
        2=>"of",
        3=>"times,
        4=>123
   )
);

I would appreciate any and all help sorting them and pushing them into the new array in order.

You can use usort() to sort the array however you'd like, and end() gets the last value in the array etc. so this would sort the array of arrays by the last index in each array, highest first : 您可以使用usort()对数组进行排序,而end()获取数组中的最后一个值,依此类推。这样就可以按照每个数组中的最后一个索引对数组进行排序,最高的是first:

function cmp($a, $b) {
    if (end($a) == end($b)) {
        return 0;
    }
    return (end($a) > end($b)) ? -1 : 1;
}

usort($twoDUnsorted, "cmp");

There is already a multi-dimensional sort function. 已经有一个多维排序功能。 I think the third example on this page should help you. 我认为此页面上的第三个示例应该会对您有所帮助。

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

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