phparrayssortingmultidimensional-array

Sorting a 2D array by a column


Trying to sort an array by name so I can display an alphabetical list.

Here's a snippet of code:

sort($stores);

for ($i = 0; $i < count($stores); $i++) {
    echo $stores[$i]['name'];
}

I have a basic understanding of what needs to be done, I'm just not sure how to pass the 'name' part of the array to the sort() function. Perhaps I need to use a different function?


Solution

  • Use a custom sort function:

    usort($stores, function ($a, $b) {
        return strcmp($a['name'], $b['name']);
    });