简体   繁体   English

使用 PHP 对字符串数组进行排序

[英]Sort string array with PHP

I have an ID:Name Array我有一个 ID:Name 数组

example:例子:

$datas = array();
$datas[2345] = "Banana";
$datas[5740] = "Apple";
$datas[98763]= "Orange";

My final but is to sort the array alphabetically.我的最终目的是按字母顺序对数组进行排序。

var_dump($datas);
//"4536" => "Apple", "2345" => Banana", "98763" => "Orange"

I try with usort but it's not working.我尝试使用 usort,但它不起作用。

 usort($datas, function ($a, $b) {
            return strcasecmp($a,$b);
        });

How can I sort alphabetically that king of arrays?如何按字母顺序对数组之王进行排序?

使用asort函数:

asort($datas);

You don't even need a usort simply use asort as你甚至不需要一个usort只需使用asort作为

asort($datas);

Or you can simply use uasort instead of usort as you need to have your keys also so simply use as或者您可以简单地使用uasort而不是usort因为您也需要拥有您的密钥,所以只需使用 as

uasort($datas,'strcasecmp');

asort is what you're looking for, it will sort it alphabetically as you can see below. asort是您要查找的内容,它将按字母顺序排序,如下所示。

$datas = array();
$datas[2345] = "Banana";
$datas[5740] = "Apple";
$datas[98763]= "Orange";

asort($datas);

var_dump($datas);

array(3) { [5740]=> string(5) "Apple" [2345]=> string(6) "Banana" [98763]=> string(6) "Orange" }
asort(); 

From PHP Manual来自 PHP 手册

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with.此函数对数组进行排序,以便数组索引保持与其关联的数组元素的相关性。 This is used mainly when sorting associative arrays where the actual element order is significant.这主要用于对实际元素顺序很重要的关联数组进行排序时。

$datas = array();
$datas[2345] = "Banana";
$datas[5740] = "Apple";
$datas[98763]= "Orange";

asort($datas);

Now when you wish to see the output with var_dump($datas);现在,当您希望使用var_dump($datas);查看输出时var_dump($datas); you'd see:你会看到:

array(3) {[5740]=> string(5) "Apple" [2345]=> string(6) "Banana" [98763]=> string(6) "Orange"}

Use asort() from php array functions使用 php 数组函数中的asort()

Please refer Array Functions请参考数组函数

    <?php
    $datas = array();
    $datas[2345] = "Banana";
    $datas[5740] = "Apple";
    $datas[98763]= "Orange";

    asort($datas);

    print_r($datas);
    //Array ( [5740] => Apple [2345] => Banana [98763] => Orange )

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

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