-->

Sorting a multidimensional array in PHP? [duplicat

2019-01-02 22:02发布

问题:

This question already has an answer here:

  • How can I sort arrays and data in PHP? 9 answers

I have this kind of an array

array(5) {
  [0]=>
  array(5) {
    [0]=>
    string(7) "jannala"
    [1]=>
    string(10) "2009-11-16"
    [2]=>
    string(29) "
            <p>Jotain mukavaa.</p>
        "
    [3]=>
    int(12)
    [4]=>
    int(1270929600)
  }
  [1]=>
  array(5) {
    [0]=>
    string(7) "jannala"
    [1]=>
    string(10) "2009-11-16"
    [2]=>
    string(51) "
            <p>Saapumiserä II/09 astuu palvelukseen</p>
        "
    [3]=>
    int(11)
    [4]=>
    int(1270929600)
  }
  ...
}

What I need to be done is to sort the array based on array's [x][4] (the unix timestamp value). How would I achieve this?

回答1:

use a compare function, in this case it compares the array's unix timestamp value:

function compare($x, $y) {
if ( $x[4] == $y[4] )
return 0;
else if ( $x[4] < $y[4] )
return -1;
else
return 1;
}

and then call it with using the usort function like this:

usort($nameOfArray, 'compare');

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Taken from PHP: usort manual.



回答2:

Just my initial thought: wrap each of the nested arrays in an object(instance of class), so that once sorted by a specific field(in this case, the unix time stamp), you can easily access the other information by using the same object reference.

So your nested array of arrays might become an array of objects, each of which has a "sort" method.



回答3:

I was struggling with the "compare" function above, but was able to get this working:

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

usort($array, "cmp");

(Note that this is also a descending, not ascending, sort.)



标签: