-2

If I have an array with objects like this:

Array
(
    [0] => stdClass Object
        (
            [img] => image1.jpg
            [order] => 1
        )

    [1] => stdClass Object
        (
            [img] => image2.jpg
            [order] => 3
        )

    [2] => stdClass Object
        (
            [img] => image3.jpg
            [order] => 2
        )

    [3] => stdClass Object
        (
            [img] => image4.jpg
            [order] => 4
        )
)

How can I then sort the array by the objects "order" value? In this case the order should be: image1.jpg, image3.jpg, image2.jpg, image4.jpg.

halfer
  • 19,824
  • 17
  • 99
  • 186
gubbfett
  • 2,157
  • 6
  • 32
  • 54

3 Answers3

1

Here is an exemple for your code :

function sortImage($a, $b)
{
    if ($a->img == $b->img) {
        return 0;
    }
    return ($a->img < $b->img) ? -1 : 1;
}


usort($youArray, "sortImage");

edit: in your case you have order property but php can also compare "image1" and "image2" strings

Sidux
  • 557
  • 1
  • 5
  • 15
0

You should use this function: http://php.net/manual/en/function.usort.php

You have to write a comparison function, to be used as the second argument to usort.

ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
0

PHP 5.3+

usort($myArray, function ($a, $b) {
    if ($a->order == $b->order) {
        return 0;
    }
    return ($a->order < $b->order) ? -1 : 1;
});

For < PHP 5.3 just change the anonymous function for a predefined named function.

MrCode
  • 63,975
  • 10
  • 90
  • 112