I'm breaking my head to sort array with key value. With this following array i need to sort this by site_category and i need to have output like
Example:
Shopping
Amazon
Social
Amoeblo
American express
Array values are
(
[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
)
)
Any suggestion to solve this?
Virtually a duplicate of Sort php multidimensional array by sub-value
function cmp($a, $b) {
return $a->site_category - $b->site_category;
}
usort($arr, "cmp");
You can do it using a foreach and ksort
Let $your_array be the array you mentioned above
$res_array = array();
foreach($your_array as $val){
$res_array[$val->site_category][] = $val->site_name;
}
ksort($res_array);
print_r($res_array);
OR search for multisort in php which will solve your problem :)
$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;
This sorts your $carriers
array by it's price key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.