How can I sort multidimensional array in numeric order first and then in alphabetical order in PHP. I have one array :
JavaScript
x
{
"id": "220",
"pin_list": [
{
"id": "1",
"name": "1. La Sagrada Familia",
},
{
"id": "2",
"name": "2. Park Guell",
},
{
"id": "3",
"name": "10. Casa Batllo",
},
{
"id": "4",
"name": "11. Cathedral of Barcelona",
},
{
"id": "5",
"name": "3. Picasso Museum",
},
{
"id": "6",
"name": "Zebra",
},
{
"id": "7",
"name": "Apple",
},
{
"id": "8",
"name": "Monkey",
}
]
}
I want this array to sort in Numeric first and rest are in alphabetical order. So basically want array output like this :
JavaScript
{
"id": "220",
"pin_list": [
{
"id": "1",
"name": "1. La Sagrada Familia",
},
{
"id": "2",
"name": "2. Park Guell",
},
{
"id": "5",
"name": "3. Picasso Museum",
},
{
"id": "3",
"name": "10. Casa Batllo",
},
{
"id": "4",
"name": "11. Cathedral of Barcelona",
},
{
"id": "7",
"name": "Apple",
},
{
"id": "8",
"name": "Monkey",
},
{
"id": "6",
"name": "Zebra",
}
]
}
I tried natsort and array_multisort but not able to get desired output. Any idea how to do this?
Advertisement
Answer
You can use usort
on the pin_list
element of the array (assuming you have decoded this JSON to an associative array), using strnatcmp
to compare the name
values:
JavaScript
usort($array['pin_list'], function ($a, $b) {
return strnatcmp($a['name'], $b['name']);
});