有一個例外的數組比方說,我有一個數組名爲$陣列看起來像這樣一次我就可以ASORT運行:如何排序在PHP
Array
(
[1] => Apples
[2] => Bananas
[3] => Cherries
[4] => Donuts
[5] => Eclairs
[6] => Fried_Chicken
)
是什麼讓這個最簡單的方法,按字母順序排序後,具有值「甜甜圈」的鍵被刪除,然後放在結尾?
有一個例外的數組比方說,我有一個數組名爲$陣列看起來像這樣一次我就可以ASORT運行:如何排序在PHP
Array
(
[1] => Apples
[2] => Bananas
[3] => Cherries
[4] => Donuts
[5] => Eclairs
[6] => Fried_Chicken
)
是什麼讓這個最簡單的方法,按字母順序排序後,具有值「甜甜圈」的鍵被刪除,然後放在結尾?
我想出了這個。測試它並確認它有效。重新排序陣列,以便我可以看到排序。
$arr = Array(
1 => "Fried_Chicken",
2 => "Donuts",
3 => "Bananas",
4 => "Apples",
5 => "Eclairs",
6 => "Cherries"
);
// Get donut and key
$donut_key = array_search("Donuts", $arr);
$donut = $arr[$donut_key]; // If you don't need to keep the value, skip this line
// Remove donut
unset($arr[$donut_key]);
// Sort
asort($arr);
// Append Donut
$arr += array($donut_key => $donut);
陣列搜索 http://php.net/manual/en/function.array-search.php
主要保留追加 http://www.vancelucas.com/blog/php-array_merge-preserving-numeric-keys/
我會簡單地刪除甜甜圈元素,執行您的asort
,然後重新添加甜甜圈項目。
+1打我一拳。 –
我從可變數據中獲得這個數組,因此下次運行這個時,Donuts可能是#2或#8,所以我不能取消設置($ array [4])。 –
您不需要'unset($ array [4])''''''''''''''''''''''''它可能需要2分鐘的谷歌搜索找到一個適合您的需求。 –
謝謝,這也是我最終做的。 –
是的,花了我多一點時間比我計劃......對此感到遺憾。只是想到一個完整的代碼示例將有助於未來的谷歌 – livingparadox