【发布时间】:2021-11-16 23:59:58
【问题描述】:
我有一个存储为 $product_categories 的数组。该数组的一个示例是:
$array = [
[
['id' => 10, 'text' => 'Latex'],
['id' => 15, 'text' => 'Occasion Latex'],
['id' => 82, 'text' => 'Christmas'],
],
[
['id' => 11, 'text' => 'Accessories'],
['id' => 97, 'text' => 'Retail Accessories'],
['id' => 558, 'text' => 'Super Stuffer'],
],
[
['id' => 374, 'text' => 'Party Supplies'],
['id' => 1488, 'text' => 'Party by Occasion'],
['id' => 1493, 'text' => 'Christmas'],
],
];
我只想按 [0] 中的“文本”键对其进行排序,这会给我一个结果
[
[
['id' => 11, 'text' => 'Accessories'],
['id' => 97, 'text' => 'Retail Accessories'],
['id' => 558, 'text' => 'Super Stuffer'],
],
[
['id' => 10, 'text' => 'Latex'],
['id' => 15, 'text' => 'Occasion Latex'],
['id' => 82, 'text' => 'Christmas'],
],
[
['id' => 374, 'text' => 'Party Supplies'],
['id' => 1488, 'text' => 'Party by Occasion'],
['id' => 1493, 'text' => 'Christmas'],
],
];
我试过了
$product_categories = usort($product_categories, 'sortAlphabetically');
function sortAlphabetically($a, $b) {
return strcmp($a['text'], $b['text']);
}
使用它,数组的 print_r() 简单地返回
1.
我认为usort() 是对数组进行排序的正确方法,但显然我在这里做错了。
【问题讨论】:
-
usort()对数组进行就地排序并返回TRUE,它不返回排序后的数组。 -
$a['text']应该是$a[0]['text'],如果你想按[0]中的文本排序,$b也是如此。