I use array_multisort() function to sort an array by a field value. what I need is to sort it by 2 field values, by date and by time.
here is the structure of the array:
Array
(
[0] => Array
(
[id_art] => 5292
[free_art] => 0
[apero_art] => 0
[name_cat] => Teatro
[date_dat] => 2010-11-24
[date2_dat] => 0000-00-00
[name_spa] => Cinema Teatro
[title_int] => Il piacere dell'onestÃ
[id_cat] => 2
[time_tim] => 20:30:00
[intro_int] => Una produzione Teatro Eliseo di Roma - ChiassoCultura
[image_art] => noimage.png
)
[1] => Array
(
[id_art] => 4983
[free_art] => 0
[apero_art] => 0
[name_cat] => Cinema
[date_dat] => 2011-04-20
[date2_dat] => 2011-04-20
[name_spa] => Cinema Morettina
[title_int] => Inland Empire
[id_cat] => 1
[time_tim] => 20:30:00
[intro_int] => Rassegna dedicata a David Lynch
[image_art] => noimage.png
)
[2] => Array
(
[id_art] => 4983
[free_art] => 0
[apero_art] => 0
[name_cat] => Cinema
[date_dat] => 2011-04-22
[date2_dat] => 2011-04-22
[name_spa] => Cinema Iride
[title_int] => Inland Empire
[id_cat] => 1
[time_tim] => 17:00:00
[intro_int] => Rassegna dedicata a David Lynch
[image_art] => noimage.png
)....
What I do now is:
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
How can I easily make in one time the double sort?
Thanks.
If I understand what you need to do, you can use usort:
The way your function works it a bit twisty, to me.
You extract a column of your array to create an array to sort linked to the original array. It took several readings and a php manual check to understand your code (too bad), you should have (to me) detach the creation of the index array into another function prior than calling the sort.
If you need to have dynamic colums selection maybe you can leverage on closures (PHP 5.3+ ?):
And then you can call the function like this: