简体   繁体   English

多维PHP数组的基本排序

[英]Basic sorting of a multi-dimensional PHP array

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. 我对需要做什么有一个基本的了解,我只是不确定如何将数组的'name'部分传递给sort()函数。 Perhaps I need to use a different function? 也许我需要使用不同的功能?

Thanks. 谢谢。

Use a custom sort function : 使用自定义排序功能

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

You can use usort to sort an array by values using a customized comparison function. 您可以使用usort使用自定义比较函数按值对数组进行排序。

By custom here we mean an array of custom object types. 通过自定义,我们指的是一组自定义对象类型。

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

usort($stores, "compare");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM