按键对PHP中的数组进行排序

时间:2011-12-11 07:33:46

标签: php arrays sorting

这是我的数组,我们称之为$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 ) )

我想用键#34; city"来排序这个数组。按升序排列所以数组将是:

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 ) )

然后我想按状态键值按升序排序数组,所以它看起来像这样:

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 ) )

6 个答案:

答案 0 :(得分:1)

你需要使用带回调的usort。

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

匿名函数仅在php 5.3起作用,所以万一你使用旧的东西将回调移动到一个新函数:

function my_array_sort_callback($a, $b) {
    return (strcmp ($a ['city'], $b ['city']))
}

usort ($array, "my_array_sort_callback");

答案 1 :(得分:1)

检查array_multisort的示例#3:http://www.php.net/manual/en/function.array-multisort.php

答案 2 :(得分:0)

首先将数组存储在变量中然后运行循环

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

输出将是     a =橙色     b =香蕉     c =苹果     d =柠檬

答案 3 :(得分:0)

试试这个,假设$ arr是你的数组而不是

foreach($arr as $k=>$v):
ksort($v);
endforeach;

print_r($arr);

答案 4 :(得分:0)

答案 5 :(得分:0)

这是一个解决您问题的解决方案:

<?php

$arr = array(
    array("posts"=>323, "city"=>"london"),
    array("posts"=>223, "city"=>"birmingham"),
    array("posts"=>255, "city"=>"norwich"),
    array("posts"=>13, "city"=>"manchester"),
    array("posts"=>23, "city"=>"liverpool"),
);

function cmp($a, $b) 
{
        return ($a["posts"] >= $b["posts"]);
}


usort($arr, "cmp");

print_r($arr);
?>