Search code examples
phpsortingstrcmpusort

Trying to use usort with strcmp to sort objects by property


Looking at this post it seemed pretty straight forward, but I can't get this working.

I build an array of objects like this:

objs = array();
loop..
$obj = array(
    "prop1" => 'cccc a a a a 32423f sdf',
    "prop2" => 'sdlkfjsldkfj',
    "prop3" => 'slkfjs93s3jfsl'
);
$Objs[] = $obj2;

Then I attempt to sort the objects alphabetically on a property:

function cmp($a, $b) {
    return strcasecmp($a->prop1, $b->prop1);
}
usort($fileObjs, "cmp");

But it does not sort them alphabetically not sure where I went wrong. here is a complete example:

$objs = array();
$obj1 = array(
    "prop1" => 'aaaa a a a a 32423f sdf',
    "prop2" => 'sdlkfjsldkfj',
    "prop3" => 'slkfjs93s3jfsl'
); 
$obj2 = array(
    "prop1" => 'bbb a a a a 32423f sdf',
    "prop2" => 'sdlkfjsldkfj',
    "prop3" => 'slkfjs93s3jfsl'
); 
$obj3 = array(
    "prop1" => 'cccc a a a a 32423f sdf',
    "prop2" => 'sdlkfjsldkfj',
    "prop3" => 'slkfjs93s3jfsl'
); 
$objs[] = $obj2;
$objs[] = $obj1;
$objs[] = $obj3;

function cmp($a, $b) {
    return strcasecmp($a->prop1, $b->prop1);
}
usort($objs, "cmp");
var_dump($objs);

And the resulting output:

array(3) {
  [0]=>
  array(3) {
    ["prop1"]=>
    string(23) "cccc a a a a 32423f sdf"
    ["prop2"]=>
    string(12) "sdlkfjsldkfj"
    ["prop3"]=>
    string(14) "slkfjs93s3jfsl"
  }
  [1]=>
  array(3) {
    ["prop1"]=>
    string(23) "aaaa a a a a 32423f sdf"
    ["prop2"]=>
    string(12) "sdlkfjsldkfj"
    ["prop3"]=>
    string(14) "slkfjs93s3jfsl"
  }
  [2]=>
  array(3) {
    ["prop1"]=>
    string(22) "bbb a a a a 32423f sdf"
    ["prop2"]=>
    string(12) "sdlkfjsldkfj"
    ["prop3"]=>
    string(14) "slkfjs93s3jfsl"
  }
}

Solution

  • It seems your confusing objects and arrays objects. Your cmp function is comparing properties that don't exist in your arrays objects.

    if you :

    echo "comparing {$a->prop1} vs {$b->prop1}";
    

    in the cmp method you'll notice the prop1's are null.

    You can fix your code by referencing the array index like this

    function cmp($a, $b) {
        return strcasecmp($a['prop1'], $b['prop1']);
    }