Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this array:

    Array
(
    [0] => stdClass Object
        (
            [ID] => 1206
            [post_title] => Corporation 5
            [zip_code] => 33017
            [miles] => 13.24
        )

    [1] => stdClass Object
        (
            [ID] => 1197
            [post_title] => Contract deal
            [zip_code] => 33432
            [miles] => 22.7
        )

    [2] => stdClass Object
        (
            [ID] => 1057
            [post_title] => Corporation Deal test1
            [zip_code] => 33019
            [miles] => 0
        )

    [3] => stdClass Object
        (
            [ID] => 1040
            [post_title] => Bankruptcy Deal1 test lorem ipsum
            [zip_code] => 33019
            [miles] => 0
        )

    [4] => stdClass Object
        (
            [ID] => 993
            [post_title] => Finally an Affordable Living Trust, Only $100!
            [zip_code] => 33019
            [miles] => 0
        )

)

And I want results sort by "miles".

How can I do that?

share|improve this question
1  
A first step would be to include a member called "miles" in the objects I'd say... – fvu Jul 25 '12 at 11:52
But where are miles – Ankit Jul 25 '12 at 11:52
miles ?? based on zipcode ,we have to calculate miles and then sort out ?? – Makesh Jul 25 '12 at 11:53
@fvu - sorry, added miles. – CroiOS Jul 25 '12 at 11:57
PHP sort multidimensional array - stackoverflow.com/questions/2699086/… – Chief17 Jul 25 '12 at 11:59

2 Answers

up vote 4 down vote accepted

You can use the usort function

function Compare($a, $b) { return $a->miles < $b->miles; }
usort($results, 'Compare');
share|improve this answer
1  
great, it work's. – CroiOS Jul 25 '12 at 12:06
public function subval_sort($a, $subkey) {       
    foreach($a as $k=>$v) {
    $b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
    $c[] = $a[$key];
}

return $c;
}

Function that sorts array by its array subvalue. $a is array passed and $subkey is array key by which it will be sorted.

share|improve this answer
Great, work's for array but not for my array which has object. – CroiOS Jul 25 '12 at 11:59
You can try editing this a bit. – Daniels Pitkevičs Jul 25 '12 at 11:59
@DanielsPitkevičs he wants to sort objects, not subarrays – fvu Jul 25 '12 at 12:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.