[英]Sort Array by key value PHP
我有這個數組:
Array
(
[Alben] => Array
(
[Sgt._Pepper’s_Lonely_Hearts_Club_Band] =>
[Rubber_Soul] =>
[Please_Please_Me] =>
[Let_It_Be_(Album)] =>
[With_the_Beatles] =>
[Let_It_Be…_Naked] =>
[A_Hard_Day’s_Night_(Album)] => Rickenbacker_360-12WB_12_String.jpg
[Beatles_for_Sale] =>
[Help!_(Album)] => Semaphore_Victor.svg
[Magical_Mystery_Tour_(Album)] =>
[The_Beatles_(Album)] =>
[Yellow_Submarine] =>
[Abbey_Road] => The_End.jpg
[Revolver_(Album)] =>
[Anthology_(The_Beatles)] =>
[A_Collection_of_Oldies_…_but_Goldies] =>
[1_(Album)] =>
)
)
現在,我想按值對它進行排序。 因此,這些鍵是第一個在值中具有img的鍵。 以及沒有這些條目的條目。 我嘗試了array_values
但它返回了相同的Array。 也許會導致鑰匙“ Alben
”?
我試過了:
$returnArray = array_values($returnArray);
array_values
將返回僅包含值的數組,並破壞關聯。 您可能需要使用uasort
函數來執行此操作,在這里您可以為值提供自定義排序邏輯並維護索引關聯。 從PHP Docs:
此函數使用用戶定義的比較函數對數組進行排序,以使數組索引保持與與其關聯的數組元素的相關性。
這主要用於對實際元素順序很重要的關聯數組進行排序時。
(從它的推導中得出usort
:)
value_compare_func
如果第一個參數分別小於,等於或大於第二個參數,則比較函數必須返回小於,等於或大於零的整數。
這是您提供的代碼的示例:
<?php
// array reproducing
$collection = array(
"Alben" => array (
"Sgt._Pepper’s_Lonely_Hearts_Club_Band" => "",
"Rubber_Soul" => "",
"Please_Please_Me" => "",
"Let_It_Be_(Album)" => "",
"With_the_Beatles" => "",
"Let_It_Be…_Naked" => "",
"A_Hard_Day’s_Night_(Album)" => "Rickenbacker_360-12WB_12_String.jpg",
"Beatles_for_Sale" => "",
"Help!_(Album)" => "Semaphore_Victor.svg",
"Magical_Mystery_Tour_(Album)" => "",
"The_Beatles_(Album)" => "ble_test",
"Yellow_Submarine" => "",
"Abbey_Road" => "The_End.jpg",
"Revolver_(Album)" => "",
"Anthology_(The_Beatles)" => "",
"A_Collection_of_Oldies_…_but_Goldies" => "",
"1_(Album)" => "",
));
// callback of sorting, checks if the compared value is not empty then pushes it ahead.
// If not, pull it backwards.
$sortIfFilled = function ($a, $b) {
return (!$a) ? 1 : -1;
};
// Executing it...
uasort($collection['Alben'], $sortIfFilled);
echo "<pre>";
print_r ($collection);
輸出:
Array
(
[Alben] => Array
(
[The_Beatles_(Album)] => ble_test
[Abbey_Road] => The_End.jpg
[A_Hard_Day’s_Night_(Album)] => Rickenbacker_360-12WB_12_String.jpg
[Help!_(Album)] => Semaphore_Victor.svg
[Yellow_Submarine] =>
[Let_It_Be…_Naked] =>
[A_Collection_of_Oldies_…_but_Goldies] =>
[Let_It_Be_(Album)] =>
[Revolver_(Album)] =>
[Beatles_for_Sale] =>
[With_the_Beatles] =>
[Sgt._Pepper’s_Lonely_Hearts_Club_Band] =>
[Rubber_Soul] =>
[Magical_Mystery_Tour_(Album)] =>
[Anthology_(The_Beatles)] =>
[Please_Please_Me] =>
[1_(Album)] =>
)
)
請仔細閱讀PHP Docs上的回調函數,它們可能會幫助您解決項目中的類似問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.