php - Sorting subarray by lastname
Get the solution ↓↓↓I have an array that I have sorted by year within which I have arrays with a lastname key. I am looking to sort these subarrays by lastname.
I managed to classify by year. But the arrays inside are not sorted by lastname.
[
"1946" => [
[
"firstname" => "Juan",
"lastname" => "Darcy"
], [
"firstname" => "Franck",
"lastname" => "Bolly"
]
],
"1945" => [
[
"firstname" => "Pierre",
"lastname" => "Carry"
], [
"firstname" => "Catherine",
"lastname" => "Aarron"
]
]
]
I would to reorder array by lastname without changing the order of the years, like that :
[
"1946" => [
[
"firstname" => "Franck",
"lastname" => "Bolly"
], [
"firstname" => "Juan",
"lastname" => "Darcy"
]
],
"1945" => [
[
"firstname" => "Catherine",
"lastname" => "Aarron"
], [
"firstname" => "Pierre",
"lastname" => "Carry"
]
]
]
I tried this:
$alumnis_array_number = [];
foreach ($alumnis_array_year as $value) {
$year = $value['year'];
$alumnis_array_number[$year][] = $value;
}
uasort($alumnis_array_number, function($a, $b) {
return strcasecmp($a['lastname'], $b['lastname']);
});
But I got
Undefined index: lastname
How can I get those subarrays sorted by lastname?
Answer
Solution:
It seems easier to perform the sort before you group the data by year. So you would sort$alumnis_array_year
before executing the code you quoted in your question:
uasort($alumnis_array_year, function($a, $b) {
$diff = $b["year"] - $a["year"];
if ($diff) return $diff;
$diff = strcasecmp($a['lastname'], $b['lastname']);
if ($diff) return $diff;
return strcasecmp($a['firstname'], $b['firstname']);
});
If you do this first and then execute your code, it will be OK.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.