PHP 按字段排序数组?

2022-08-30 09:56:21

可能的重复:
如何按内部键
对多维数组进行排序 如何在php中对数组数组进行排序?

如何对数组进行排序,如下所示:$array[$i]['title'];

数组结构可能如下所示:

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'
);

因此,数据是根据数组中的标题字段以ASC顺序显示的吗?


答案 1

使用为此目的明确构建的 usort

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

usort($array, "cmp");

答案 2