我正在寻求帮助。我找到了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), /* ... */
)
你能给我一个如何解决这个问题的提示吗?
答案 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)