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?

2

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.