在数组数组中按键排序php数组

时间:2012-05-17 20:00:00

标签: php arrays sorting

我正在寻求帮助。我找到了ksort和其他排序方法的PHP。但我在一个数组中得到一个数组,其中包含一个名为order的密钥。这我想成为数组的顺序

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), /* ... */
)

现在我希望数组对象按此排序:

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), /* ... */
)

你能给我一个如何解决这个问题的提示吗?

3 个答案:

答案 0 :(得分:0)

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

usort($array, "cmp");

print_r ($array);

答案 1 :(得分:0)

一个相当简单的解决方案是使用数组索引本身来存储顺序,然后使用sort按顺序对数组进行排序,然后array_values重新索引它?

答案 2 :(得分:0)

array_multisort可能对您有效:

将数组称为$ myArray

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

array_multisort($order, SORT_ASC, $myArray)