The solution is to use the function usort
or uasort
, which use a callback to use specific sort rules:
usort( $res, 'compara' );
uasort( $res, 'compara' );
In the above case, we are saying that the order defines the function compara
.
The basic difference between the two is that uasort
preserves the original indexes, and usort
does not.
The function whose name is passed in usort
or uasort
is called successively with two original array items by time, and you must return 0
, a negative number or a number positive for the case of tie, in order or out of order respectively.
In turn, within the compara()
function, we will fix the order of its "date" and concatenate with time, and then return the comparison between the resulting strings using strcmp
, which just returns 0
+n
and -n
as desired:
function compara( $a1, $a2 ) {
$ts1 = substr($a1[0],6,4).substr($a1[0],3,2).substr($a1[0],0,2).$a1[1];
$ts2 = substr($a2[0],6,4).substr($a2[0],3,2).substr($a2[0],0,2).$a2[1];
return strcmp($ts1, $ts2);
}
See working with uasort
on IDEONE .
Compare with usort
, also in IDEONE .
Just to better detail the above function, see how the strings are mounted:
item [0] 14/08/2013
posição 0123456789
quantidade de caracteres 2c 2c 4c
item [1] 12:36
item [2] SILMARA
substr($a1[0],6,4) . substr($a1[0],3,2) . substr($a1[0],0,2) . $a1[1]
└───── ANO ──────┘ └───── MÊS ──────┘ └───── DIA ──────┘ └ HORA ┘
└────────────────────────── Item 0 ──────────────────────────┘└ Item 1 ┘
Resultado 2013081412:36
PHP Manual: