按值按字母顺序排序数组php

hgc7kmma  于 2023-01-08  发布在  PHP
关注(0)|答案(5)|浏览(169)

正如标题所示,我想在php中按值的字母顺序对数组进行排序。

$arr = array(
    'k' => 'pig',
    'e' => 'dog'
)

会变成

$arr = array(
    'e' => 'dog',
    'k' => 'pig'
)

有什么想法吗?
编辑:这是我想要排序的实际数组。

Array ( [0] => Newtown [1] => Montgomery [2] => Welshpool [6] => Llanfyllin [7] => Llansanffraid [8] => Llanymynech [9] => Oswestry [14] => Oswestry Town Service [15] => Aston Way [16] => College Road [17] => Shrewsbury [18] => Royal Shrewsbury Hospital [19] => Worthen [20] => Brockton [22] => Cefn Blodwell [23] => Treflach [24] => Trefonen [25] => Morda [26] => Marches School [28] => North Shropshire College [37] => Park Hall [38] => Gobowen [39] => St Martins [40] => Ifton Heath [42] => Guilsfield [43] => Four Crosses [45] => Pant [46] => Llynclys [49] => Oswestry Town Service Schools [51] => Woodside School [56] => Whittington [57] => Babbinswood [58] => Hindford [59] => Ellesmere [62] => Forden [63] => Kingswood Cock Hotel [65] => Coleg Powys [85] => Borfa Green [86] => Bryn Siriol [87] => Maesydre School [92] => Crew Green [93] => Ford [104] => Llanrhaeadr [106] => Meifod [114] => Llangynog [116] => Llangedwyn [119] => Porthywaen [132] => Llanfair Caereinion [133] => Pontrobet [136] => Dolanog [141] => Llansilin [144] => Abermule [145] => Llandyssil [146] => Carhowel [149] => Cefn Coch [150] => Tregynon [151] => Manafon [152] => Berriew [157] => Bettws Cedewain [158] => Newtown High School [160] => Newtown Coleg Powys [173] => Llanerfyl [174] => Machynlleth [175] => Talybont [176] => Aberystwyth [183] => Bala [184] => Llanrwst [185] => Llandudno [188] => Middletown [196] => Llanidloes [202] => Wrexham [203] => Rhayader )
2eafrhcq

2eafrhcq1#

你需要php函数“asort”:
http://php.net/manual/en/function.asort.php
它对数组进行排序,同时维护索引关联。
编辑:我刚刚注意到你使用的是一个标准的数组(非关联的),如果你不介意保留索引关联,可以使用sort():
http://php.net/manual/en/function.sort.php

olhwl3o2

olhwl3o22#

注意,sort()对数组 in place 进行操作,因此您只需调用

sort($a);
doSomething($a);

这行不通;

$a = sort($a);
doSomething($a);
4bbkushb

4bbkushb3#

  • 如果你只想对数组值进行排序,而不关心键,那么使用sort(),这将给予一个新的数组,其数字键从0开始。
  • 如果希望保留键值关联,请使用asort()

另请参见comparison table of sorting functions in PHP

uqdfh47h

uqdfh47h4#

asort()-维护密钥关联:* * 是的**。
sort()-维护密钥关联:* * 没有**。
来源:http://php.net/manual/en/array.sorting.php

91zkwejq

91zkwejq5#

使用sort()函数,我有:

$array = [
    "Tannois",
    "Bar-le-Duc",
    "Val-d'Ornain",
    "Fains-Véel",
    "Érize-Saint-Dizier",
    "Ville-sur-Saulx",
    "Seigneulles",
    "Behonne"
];
sort($array);

结果为:

[
    "Bar-le-Duc",
    "Behonne",
    "Fains-Véel",
    "Seigneulles",
    "Tannois",
    "Val-d'Ornain",
    "Ville-sur-Saulx",
    "Érize-Saint-Dizier"
]

Érize-Saint-Dizier是最后一个。
我可以这样排序:

[
    "Bar-le-Duc",
    "Behonne",
    "Érize-Saint-Dizier",
    "Fains-Véel",
    "Seigneulles",
    "Tannois",
    "Val-d'Ornain",
    "Ville-sur-Saulx"
]

相关问题