0

我正在用键值对数组进行排序。使用以下数组,我需要按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
        )


)

有什么建议可以解决这个问题吗?

4

3 回答 3

3

几乎是按子值排序php多维数组的副本

function cmp($a, $b) {
        return $a->site_category - $b->site_category;
}
usort($arr, "cmp");
于 2013-01-09T10:00:17.790 回答
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 来解决你的问题:)

于 2013-01-09T10:18:58.227 回答
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这将通过它的价格键对您的数组进行排序。

于 2014-11-27T13:25:52.823 回答