0

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Carolina
  • 207
  • 2
  • 8
  • 23
  • 1
    So many answers to this already http://stackoverflow.com/questions/2699086/sort-multidimensional-array-by-value-2 http://stackoverflow.com/questions/4508145/sort-php-multidimensional-array-by-sub-value http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php – Popnoodles Jan 09 '13 at 09:58
  • 1
    first problem: these aren't arrays, they're objects. They may usually behave like arrays, but not always. `site_category` isn't an array key it's an object property – RockyFord Jan 09 '13 at 10:29

3 Answers3

3

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");
Community
  • 1
  • 1
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
2

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 :)

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
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;

This sorts your $carriers array by it's price key.

Bowdzone
  • 3,827
  • 11
  • 39
  • 52
Vipul Hadiya
  • 882
  • 1
  • 11
  • 22