# Sort array based on 2 conditions

if I have a multidimensional array in the form of:

``````
[0] => stdClass Object ( [condition1] => 200 [con2] => -1)
[1] => stdClass Object ( [condition1] => 3 [con2] => 0)
[2] => stdClass Object ( [condition1] => 554 [con2] => -3)
[3] => stdClass Object ( [condition1] => 89 [con2] => -2)
[4] => stdClass Object ( [condition1] => 1 [con2] => 0)
[5] => stdClass Object ( [condition1] => 306 [con2] => -4)

``````

basically first I want to order them in an ascending way which I already have based on cond2 which is my first priority so they are in the order of -4, -3, -2, -1, 0, 0 etc.

Then the ones that have cond2 set to 0 I need to order them ascending based on condition1 so at the end I would have something like this:

``````
[5] => stdClass Object ( [condition1] => 306 [con2] => -4)
[2] => stdClass Object ( [condition1] => 554 [con2] => -3)
[3] => stdClass Object ( [condition1] => 89 [con2] => -2)
[0] => stdClass Object ( [condition1] => 200 [con2] => -1)
[4] => stdClass Object ( [condition1] => 1 [con2] => 0)
[1] => stdClass Object ( [condition1] => 3 [con2] => 0)

``````

well in the code above the indexes are 5, 2, 3, 0 etc those are the ones I want to change 5 to 0, 2 to 1, 3 to 2, 0 to 3 etc.

You’ll have to use uasort() (PHP: uasort - Manual) and create your own function.

Your callback function would look something like this:

``````
function cmp(\$a, \$b) {
if(\$a->con2 == \$b->con2) {
if(\$a->conditional == \$b->conditional)
return 0;
return (\$a->conditional < \$b->conditional) ? 1 : -1);
}

return (\$a->con2 < \$b->con2) ? 1 : -1);
}

``````

Then you just call it like:

``````
uasort(\$myarray, 'cmp');

``````

actually I been doing that without success, I just can´t figure a way to make it work the way I want it to, it always orders the items based on the first array object property which in this case does not work for me.

I finally was able to make some progress, I was trying this:

``````
usort(\$array->ordering_value, "cmp");

``````

and I needed to add the ordering value in the function and then call the function with just the array name

thank you for your input as it helped me a lot