I do not understand the way to sort a multi-dimensional array in php. I have a structure like this:
Array (
[0] (
['vname'] => "Bernt"
['nname'] => "Mayer"
['kl_name'] => "ZR4"
)
[1] (
['vname'] => "Albert"
['nname'] => "Mayer"
['kl_name'] => "TR4"
)
)
My goal is now to first sort by kl_name
, and then by nname
and then vname
. Most important is kl_name
.
First I tought I should make objects and store them in the array, but I think sorting them is even more complex. php.net has a nice article about array_multisort, but year, I don't understand it.
You'll want to sort the array with a user defined function (with usort).
You can then manually specify how you'd like the items to be ordered using the kl_name
, nname
and vname
attributes.
Something like this:
usort($arr, function($a, $b) {
if ($a['kl_name'] !== $b['kl_name']) {
return strcmp($a['kl_name'], $b['kl_name']);
} else if ($a['nname'] !== $b['nname']) {
return strcmp($a['nname'], $b['nname']);
} else {
return strcmp($a['vname'], $b['vname']);
}
});
The function will first attempt to sort by kl_name
, then by nname
and finally by vname
if all previous values are equal.