同一陣列的頂部我有一個數組:array_push或array_unshift多行PHP
[0] => Array
(
[Id] => 1
[Order] => 1
[ContentGroupId] => 10
[ContentGroupIsNew] => 0
)
[1] => Array
(
[Id] => 2
[Order] => 2
[ContentGroupId] => 11
[ContentGroupIsNew] => 0
)
[2] => Array
(
[Id] => 3
[Order] => 3
[ContentGroupId] => 12
[ContentGroupIsNew] => 1
)
[3] => Array
(
[Id] => 4
[Order] => 4
[ContentGroupId] => 13
[ContentGroupIsNew] => 1
)
[4] => Array
(
[Id] => 5
[Order] => 5
[ContentGroupId] => 14
[ContentGroupIsNew] => 0
)
默認順序是[Order]
我要重新梳理這個陣列,使其訂單由[ContentGroupIsNew] = 1
頂部(如果存在的話,在這個樣本中2確實存在),但是保持其餘元素的現有秩序。
如果我使用usort
函數,我可以得到[ContentGroupIsNew] = 1
,但其餘的元素似乎得到隨機排序,並且不保持原來的[Order]
值。
所以,最終的結果應該是這樣的:
[0] => Array
(
[Id] => 3
[Order] => 3
[ContentGroupId] => 12
[ContentGroupIsNew] => 1
)
[1] => Array
(
[Id] => 4
[Order] => 4
[ContentGroupId] => 13
[ContentGroupIsNew] => 1
)
[2] => Array
(
[Id] => 1
[Order] => 1
[ContentGroupId] => 10
[ContentGroupIsNew] => 0
)
[3] => Array
(
[Id] => 2
[Order] => 2
[ContentGroupId] => 11
[ContentGroupIsNew] => 0
)
[4] => Array
(
[Id] => 5
[Order] => 5
[ContentGroupId] => 14
[ContentGroupIsNew] => 0
)
PHP代碼:
function sort_array($b, $a) {
return $a['ContentGroupIsNew'] - $b['ContentGroupIsNew'];
}
usort($array, 'sort_array');
你的代碼是什麼樣的?修改'usort()'函數中的條件應該很容易。 – jeroen
@jeroen添加了PHP以結束問題。 –