Reputation: 2783
---array $points----
Array
(
[0] => Array
(
[0] => 2011-10-02 05:30:00
[1] => 20
)
[1] => Array
(
[0] => 2011-10-04 09:30:00
[1] => 12
)
[2] => Array
(
[0] => 2011-10-01 13:30:00
[1] => 25
)
[3] => Array
(
[0] => 2011-10-03 02:30:00
[1] => 31
)
)
I have an array at above and would like to sort this array by time. Then I used the code as following to sort and result is correct. However, if I changed the code time[$key] = $val[0]
to $time = $val[0]
, the result is wrong.
Is there anyone can explain this to me? Many thanks!
foreach($points as $key=>$val){
$time[$key] = $val[0];
array_multisort($time, SORT_ASC, $points);
}
Upvotes: 12
Views: 21315
Reputation: 19466
The function uasort()
takes a comparison callback function. You can use this to compare two timestamps.
$arr = array(
array('2011-10-02 05:30:00','20'),
array('2011-10-04 09:30:00','12'),
array('2011-10-01 13:30:00','25'),
array('2011-10-03 02:30:00','31')
);
function timecomp($a,$b)
{
// Subtracting the UNIX timestamps from each other.
// Returns a negative number if $b is a date before $a,
// otherwise positive.
return strtotime($b[0])-strtotime($a[0]);
}
uasort($arr,'timecomp');
print_r($arr);
The above code will return
(
[1] => Array
(
[0] => 2011-10-04 09:30:00
[1] => 12
)
[3] => Array
(
[0] => 2011-10-03 02:30:00
[1] => 31
)
[0] => Array
(
[0] => 2011-10-02 05:30:00
[1] => 20
)
[2] => Array
(
[0] => 2011-10-01 13:30:00
[1] => 25
)
)
Upvotes: 6
Reputation: 42468
array_multisort
sorts more than one array at once. However, it works on an array of columns, so the foreach
loop is needed to get a column of the times. After building up this list, you can then perform the multisort. The $points
array is ordered according to the indices in $times
, as per this example in the docs.
However, you don't need to perform the sort inside the foreach
, as that means the sort happens 4 times (in your example). It only needs to happen once:
foreach ($points as $key => $val) {
$time[$key] = $val[0];
}
array_multisort($time, SORT_ASC, $points);
Upvotes: 9
Reputation: 11301
What you want to do is (basic idea):
foreach($points as $key=>$val){
$time[$val[1]] = $val[0]; // $time will be an array of [ point => time ] pairs
}
asort( $time ); // sorts the array and maintains indexes
After this you have an array of point => time
pairs, sorted by time. To get just the points, for instance do
$points = array_keys( $time );
Upvotes: -2