Scully
Scully

Reputation: 1058

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?

Upvotes: 1

Views: 56

Answers (2)

Ozair Kafray
Ozair Kafray

Reputation: 13539

You can use usort to sort an array by values using a customized comparison function.

By custom here we mean an array of custom object types.

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

usort($stores, "compare");

Upvotes: 2

deceze
deceze

Reputation: 522109

Use a custom sort function:

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

Upvotes: 2

Related Questions