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?

share|improve this question
Please chek this link for the solution : stackoverflow.com/questions/777597/… – Prasanth Bendra Feb 20 at 6:08

3 Answers

up vote 9 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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.)

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.