PHP Sort array by field?

PhpArraysSorting

Php Problem Overview


> Possible Duplicate:
> how to sort a multidemensional array by an inner key
> How to sort an array of arrays in php?

How can I sort an array like: $array[$i]['title'];

Array structure might be like:

array[0] (
  'id' => 321,
  'title' => 'Some Title',
  'slug' => 'some-title',
  'author' => 'Some Author',
  'author_slug' => 'some-author'
);

array[1] (
  'id' => 123,
  'title' => 'Another Title',
  'slug' => 'another-title',
  'author' => 'Another Author',
  'author_slug' => 'another-author'
);

So data is displayed in ASC order based off the title field in the array?

Php Solutions


Solution 1 - Php

Use usort which is built explicitly for this purpose.

function cmp($a, $b)
{
    return strcmp($a["title"], $b["title"]);
}

usort($array, "cmp");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael EcklundView Question on Stackoverflow
Solution 1 - Phpuser229044View Answer on Stackoverflow