PHP使用键值排序数组

时间:2013-01-09 09:55:34

标签: php sorting

我打破了我的头,用键值对数组进行排序。使用以下数组我需要通过 site_category 对其进行排序,我需要输出

示例:

Shopping
   Amazon
Social
   Amoeblo
   American express

数组值

(
    [0] => stdClass Object
        (
            [site_id] => 1
            [site_name] => Amazon
            [site_img] => http://localhost/faves/resource/img/sites/icon/amazon.png
            [site_category] => Shopping
        )

    [1] => stdClass Object
        (
            [site_id] => 2
            [site_name] => Ameblo
            [site_img] => http://localhost/faves/resource/img/sites/icon/ameblow.png
            [site_category] => Social
        )

    [2] => stdClass Object
        (
            [site_id] => 3
            [site_name] => American Express
            [site_img] => http://localhost/faves/resource/img/sites/icon/americanexpress.png
            [site_category] => Social
        )


)

有任何解决此问题的建议吗?

3 个答案:

答案 0 :(得分:3)

实际上是Sort php multidimensional array by sub-value

的副本
function cmp($a, $b) {
        return $a->site_category - $b->site_category;
}
usort($arr, "cmp");

答案 1 :(得分:2)

你可以使用foreach和ksort

来做到这一点

让$ your_array成为您上面提到的数组

$res_array    = array();
foreach($your_array as $val){
   $res_array[$val->site_category][] = $val->site_name;
}
ksort($res_array);

print_r($res_array);

或者在php中搜索multisort来解决你的问题:)

答案 2 :(得分:0)

$tmp = array();
$i = 0;

for($i=0;$i<count($carriers);$i++){

    for($j=$i+1;$j<count($carriers);$j++){

        if($carriers[$i]['price']>$carriers[$j]['price']){

            $tmp = $carriers[$i];
            $carriers[$i] = $carriers[$j];
            $carriers[$j] = $tmp;
        }
    }
}       
return $carriers;

这会按照它的价格键对您的$carriers数组进行排序。