Sort Multiple Array to Numeric order (1,2,…,9,10,11) and Alphabetical order in PHP

Tags: , , ,



How can I sort multidimensional array in numeric order first and then in alphabetical order in PHP. I have one array :

{
"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 :

{
"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?

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:

usort($array['pin_list'], function ($a, $b) {
    return strnatcmp($a['name'], $b['name']);
});

Demo on 3v4l.org



Source: stackoverflow