At the present time I find that I am unable to order an array of objects using one of its keys as an index to order.
Let's say the array comes like this:
Array
(
[0] => stdClass Object
(
[Id] => e6930148-319f-4b87-bb57-8aae98adfc55
[State] => FINISHED
[StartDate] => 2018-05-03T08:57:30+02:00
[EndDate] => 2018-05-03T08:59:17+02:00
)
[1] => stdClass Object
(
[Id] => 4263f6a9-6e49-4aee-bcf6-70e1d2578fc5
[State] => FINISHED
[StartDate] => 2018-05-03T10:15:39+02:00
[EndDate] => 2018-05-03T10:15:58+02:00
)
And what I need is for all the results to be ordered by the value of StartDate and descending, to always have the most recent as the first record.
I have tried generating a compare function
function comp($a, $b) {
if ($a < $b) return true;
else return false;
}
Generating a new array with the data I get
foreach ($json as $datos) {
$id = $datos->Id;
$estado = $datos->State;
$fechaIni = $datos->StartDate;
$fechaFin = $datos->EndDate;
$proceso = $datos->Configuration->ProcessId;
array_push($arrayDatos, $datos)
}
And calling her later from a uksort
uksort($arrayDAtos, comp(xxxx,yyyy))
But this is where I think I'm confused, because I don't know how to pass the necessary values to the comp function so that it orders by StartDate.
Come on, I have nothing clear about how uksort works or what exactly the comp function should do
You can indeed use
usort
, if you don't mind the (numeric) indices of the new array changing, otherwise you could useuasort
. Both functions admit a function as a parameter where we indicate how we want the order. In this case we will use ourobject_sorter
.I propose this function, somewhat advanced and certainly improvable, which offers the following advantages:
DESC
( ), for when you want to orderDESC
indentally.strnatcmp
, taking advantage of its advantages, to make the comparisons.The function is simply this:
And to use it, you just pass it the array.
To order it
ASC
endently by keyStarDate
:To order it
DESC
endently by keyStarDate
:Full test:
VER DEMO EN REXTESTER
Result:
ORIGINAL ITEM:
ASCENDING ORDER:
DESCENDING ORDER:
I hope it is useful for you.
You can do it using usort like so: