我打破了我的头,用键值对数组进行排序。使用以下数组我需要通过 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
)
)
有任何解决此问题的建议吗?
答案 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
数组进行排序。