The solution is to use the function usort
or uasort
, who use a callback to use specific sorting rules:
usort( $res, 'compara' );
uasort( $res, 'compara' );
In the above case, we are saying that who defines the order is the function compara
.
The basic difference between the two is that uasort
preserves the original indexes, and usort
nay.
The function whose name is passed on usort
or uasort
is called successively with two items of the array original for once, and you must return 0
, a negative number or positive number in the event of a tie, in order or out of order respectively.
In turn, within the function compara()
let’s fix the order of your "date" and concatenate with time, and then return the comparison between the resulting strings using strcmp
, who rightly 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
in the IDEONE.
Compare with usort
, also in the IDEONE.
Just to further 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
Manual for PHP:
The first problem is the date format you are using. Code date is desirable in YYYYMMDD format, and DD/MM/YYYY only for display. You can do what you want, but you will have to operate strings to fix these "dates" (actually they are mere strings) when ordering. Important to say in the question whether the missing hours will be first or last in the ordering.
– Bacco
This array is a Result of a Webservice I can’t handle it at the source, I would have to recreate the entire local array, which is sometimes complex, more than 3 levels merged.
– Marcelo
I posted the solution for the desired format, a functional demonstration and a brief explanation of how the string was rearranged. Perhaps it was the lack of whim of the webservice staff (but there may be some legitimate reason in rare cases, I can’t say it was certainly a failure). Any questions, ask I complement.
– Bacco