Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm searching for help. I found ksort and other sort methods for php. But i got an Array in an Array with an key called order. And this i want to be the order of the array

array(
   array("obj" => $objPage, "id" => "LogIn", "order" => 3),
   array("obj" => $objPage, "id" => "Home", "order" => 1),
   array("obj" => $objPage, "id" => "Register", "order" => 2),
   array("obj" => $objPage, "id" => "Imprint", "order" => 4), /* ... */
)

Now i want the array objects to sort as this:

array(
   array("obj" => $objPage, "id" => "Home", "order" => 1),
   array("obj" => $objPage, "id" => "Register", "order" => 2),
   array("obj" => $objPage, "id" => "LogIn", "order" => 3),
   array("obj" => $objPage, "id" => "Imprint", "order" => 4), /* ... */
)

Can you give me a hint how to solve this?

share|improve this question
add comment

3 Answers

up vote 0 down vote accepted
function cmp($a, $b)
{
    if ($a ['order'] == $b ['order']) {
        return 0;
    }
    return ($a ['order'] < $b ['order']) ? -1 : 1;
}

usort($array, "cmp");

print_r ($array);
share|improve this answer
add comment

A fairly simple solution would be to use the array index itself to store the order, then use sort to sort the array into order and then array_values to re-index it?

share|improve this answer
add comment

array_multisort may be valid for you:

Suposing your array is called $myArray

foreach ($myArray as $key => $row) {   
    $order[$key] = $row['order'];
}

array_multisort($order, SORT_ASC, $myArray)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.