php 按列值对二维数组排序

kupeojn6  于 2023-02-11  发布在  PHP
关注(0)|答案(3)|浏览(113)

我打破了我的头排序数组与关键字值。与此以下数组,我需要排序这个由网站_类别,我需要有这样的输出
示例:

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
        )

)

对此有何建议?

xnifntxz

xnifntxz1#

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

function cmp($a, $b) {
        return $a->site_category - $b->site_category;
}
usort($arr, "cmp");
06odsfpq

06odsfpq2#

您可以使用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,这将解决您的问题:)

djmepvbi

djmepvbi3#

$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数组进行排序。

相关问题