I am working with any multidimensional array Sorting when I need to sort the array with values and the values should be sorted according tot he date and time. How could I do that.
For Some situation I cant do that through Query I need to Sort through PHP Sort but the predefined function dosent help me.
My Array to be sorted:
Array
(
[events] => Array
(
[0] => Array
(
[0] => 213532
[1] => 100% View
[2] => 12/11/2014 09:00
[3] => 12/11/2014 11:00
)
[1] => Array
(
[0] => 213533
[1] => test 80
[2] => 12/11/2014 06:00
[3] => 12/11/2014 08:00
)
[2] => Array
(
[0] => 213534
[1] => wf4
[2] => 12/12/2014 00:00
[3] => 12/12/2014 23:59
)
[3] => Array
(
[0] => 213535
[1] => Standaard:
[2] => 12/12/2014 10:00
[3] => 12/12/2014 12:00
)
)
)
Every Sub Array of [2] Value.
['events'][$i][2]
Should be sorted and rearranged. in the following way.
12/11/2014 06:00
12/11/2014 09:00
12/12/2014 00:00
12/12/2014 10:00
How can I do that any logical help will be useful.
@Mario is right that usort is what you probably want. You can also use strtotime to convert the string date to an integer, which is easy to compare. I wrote up a working example here. You'll see that I first print out the data (not sorted), then call usort with my custom sort function. When I print out the array again, it's now in order by date.
function compare($a, $b) {
$timeA = strtotime($a[2]);
$timeB = strtotime($b[2]);
if ($timeA < $timeB) {
return -1;
}
if ($timeA > $timeB) {
return 1;
}
return 0;
}
function printArrayContents($arr) {
for ($i = 0; $i < count($arr); $i++) {
echo $arr[$i][2] , "<BR>";
}
}
$events = array(
0 => array(
0 => 213532,
1 => '100% View',
2 => '12/11/2014 09:00',
3 => '12/11/2014 11:00'
),
1 => array(
0 => 213533,
1 => 'test 80',
2 => '12/11/2014 06:00',
3 => '12/11/2014 08:00'
),
2 => array(
0 => 213534,
1 => 'wf4',
2 => '12/12/2014 00:00',
3 => '12/12/2014 23:59'
),
3 => array(
0 => 213535,
1 => 'Standaard:',
2 => '12/12/2014 10:00',
3 => '12/12/2014 12:00'
)
);
echo "Unsorted:<BR>";
printArrayContents($events);
if (usort($events, "compare")) {
echo "Sorted:<BR>";
printArrayContents($events);
} else {
echo "Sort failed.<BR>";
}
Output:
Unsorted:
12/11/2014 09:00
12/11/2014 06:00
12/12/2014 00:00
12/12/2014 10:00
Sorted:
12/11/2014 06:00
12/11/2014 09:00
12/12/2014 00:00
12/12/2014 10:00
0 comments:
Post a Comment