1

i have an array of objects like this : http://pastebin.ca/3217309
i want to sort this array to objects with come first then others sort by date
currently I'm using this to sort array

function cmp($a, $b)
                   {
                       return strcmp($a->date, $b->date);
                   }

                   usort($data, "cmp");

and works good but it only sort array by date and i want to in ordered array objects with pin=1 come first then other objects come after pins. i hope my question is clear,sorry for bad english !

1 Answer 1

1

If you want to sort after an other criteria, you should just add the condition to your sort function:

if ($a->pin != $b->pin) return $a->pin == 1 ? -1 : 1;

this condition only applies for $items with unequal pin properties. Combine your old compare function with this one would result in the following

function cmp($a, $b) {
    if ($a->pin != $b->pin) return $a->pin == 1 ? -1 : 1;
    return strcmp($a->date, $b->date);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks you so much , another question can i add sort direction to it ? something like we do in mysql query : ORDER BY date DESC ?
sorry found the answer my self by switching strcmp($a->date, $b->date) with strcmp($b->date, $a->date)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.