通过键排序PHP中的数组 [英] Sorting an array in PHP by key
本文介绍了通过键排序PHP中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的阵列,我们称之为 $改编
阵列([0] =>数组([文章] => 159 [城市] =>丹佛[国家] => [状态] =>科罗拉多州)
[1] =>阵列([文章] => 165 [城市] =>迈阿密[国家] =>美国[状态] =>佛罗里达州)
[2] =>阵列([文章] => 172 [城市] =>东卢瑟福[国家] =>美国[状态] =>新泽西州))
我想这个排序由数组以升序键城市这样的阵列将是:
阵列([0] =>数组([文章] => 159 [城市] =>丹佛[国家] => [状态] =>科罗拉多州)
[2] =>阵列([文章] => 172 [城市] =>东卢瑟福[国家] =>美国[状态] =>新泽西州)
[1] =>阵列([文章] => 165 [城市] =>迈阿密[国家] =>美国[状态] =>佛罗里达州))
然后我要由国家键值按升序排列数组排序也因此它看起来就像这样:
阵列([0] =>数组([文章] => 159 [城市] =>丹佛[国家] => [状态] =>科罗拉多州)
[1] =>阵列([文章] => 165 [城市] =>迈阿密[国家] =>美国[状态] =>佛罗里达州
[2] =>阵列([文章] => 172 [城市] =>东卢瑟福[国家] =>美国[状态] =>新泽西州))
解决方案
您需要用一个回调使用usort。
usort($阵列功能($ A,$ B){
回报(STRCMP($ A ['城市'],$ B ['城市']));
});
匿名函数只因为PHP 5.3工作,所以如果你使用的东西,旧的移动回调到一个新的功能:
函数my_array_sort_callback($ A,$ B){
回报(STRCMP($ A ['城市'],$ B ['城市']))
}usort($阵列my_array_sort_callback);
Here is my array, let's call it $arr
Array ( [0] => Array ( [post] => 159 [city] => Denver [country] => [state] => Colorado)
[1] => Array ( [post] => 165 [city] => Miami [country] => United States [state] => Florida )
[2] => Array ( [post] => 172 [city] => East Rutherford [country] => United States [state] => New Jersey ) )
I would like to sort this array by the key "city" in ascending order so the array will be:
Array ( [0] => Array ( [post] => 159 [city] => Denver [country] => [state] => Colorado)
[2] => Array ( [post] => 172 [city] => East Rutherford [country] => United States [state] => New Jersey )
[1] => Array ( [post] => 165 [city] => Miami [country] => United States [state] => Florida ) )
I then want to also sort the array by the state key values in ascending order so it will look like this:
Array ( [0] => Array ( [post] => 159 [city] => Denver [country] => [state] => Colorado)
[1] => Array ( [post] => 165 [city] => Miami [country] => United States [state] => Florida
[2] => Array ( [post] => 172 [city] => East Rutherford [country] => United States [state] => New Jersey ) )
解决方案
You need to use usort with a callback.
usort ($array, function ($a, $b) {
return (strcmp ($a ['city'], $b ['city']));
});
anonymous functions only work since php 5.3 so in case you use something older move the callback to a new function:
function my_array_sort_callback($a, $b) {
return (strcmp ($a ['city'], $b ['city']))
}
usort ($array, "my_array_sort_callback");
这篇关于通过键排序PHP中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文