3

I have the following object array:

 array (
   0 => MyObject::__set_state(array(
      'id' => '1176',
      'value' => 'Oranges',
   )),
   1 => MyObject::__set_state(array(
      'id' => '1178',
      'value' => 'Bananas',
   )),
   2 => MyObject::__set_state(array(
      'id' => '1179',
      'value' => 'grapes',
   )),
 )

I want to sort ascending by value so I use the following:

usort($myObjectArray, function($a, $b) {
    return strcmp($a->value, $b->value);
});  

But I'm nothing is sorted?

adam78
  • 9,668
  • 24
  • 96
  • 207

3 Answers3

0

You can do like this:

function cmp($a, $b) {
    return strcmp($a->value, $b->value);
}); 
usort($myObjectArray,"cmp");
Arijit Jana
  • 220
  • 1
  • 4
0

From php 7, you can use the spaceship operator in the comparison function.

I just tested it with the below code and it worked as you would have expected without any need to make the case uniform.

Note: I just made an array of stdClass objects by casting arrays.

$objArr = [
   (Object) [
      'id' => '1176',
      'value' => 'Oranges',
   ],
   (Object) [
      'id' => '1178',
      'value' => 'Bananas',
   ],
   (Object) [
      'id' => '1179',
      'value' => 'grapes',
   ],
];
usort($objArr, function($a, $b) {
    // use return $b->value <=> $a->value; 
    // to reverse order
    return $a->value <=> $b->value;
});

which results in the following:

print_r($objArr);

Array
(
    [0] => stdClass Object
        (
            [id] => 1178
            [value] => Bananas
        )

    [1] => stdClass Object
        (
            [id] => 1176
            [value] => Oranges
        )

    [2] => stdClass Object
        (
            [id] => 1179
            [value] => grapes
        )

)

Useful if case is an issue (i.e should grapes and Grapes be sorted).

DazBaldwin
  • 4,125
  • 3
  • 39
  • 43
0

You can try code below. I checked it's work fine:

class MyObject
{
    public $id;
    public $value;
}

$a = [];

$ob = new MyObject();
$ob->id = '1176';
$ob->value = 'Lemons';

$ob2 = new MyObject();
$ob2->id = '1178';
$ob2->value = 'apples';

$ob3 = new MyObject();
$ob3->id = '1179';
$ob3->value = 'grapes';

$a[] = $ob;
$a[1] = $ob2;
$a[2] = $ob3;

usort( $a, function($a, $b) {
    return strcmp(mb_strtolower($a->value), mb_strtolower($b->value));
});


print_r($a);

Output:

Array
(
    [0] => MyObject Object
        (
            [id] => 1178
            [value] => apples
        )

    [1] => MyObject Object
        (
            [id] => 1179
            [value] => grapes
        )

    [2] => MyObject Object
        (
            [id] => 1176
            [value] => Lemons
        )

)

Also you can check the - Doc

Dmitry Leiko
  • 3,970
  • 3
  • 25
  • 42