[英]Sorting a multidimensional array in php - by value
例如。
我有以下陣列設置,其中每個美國主要城市都有其人口規模。
$usapopstats = array(
array('New York',8008278),
array('Los Angeles',3694820),
array('Chicago',2896016),
array('Houston',1953631),
array('Philadelphia',1517550),
array('Phonenix',1321045),
array('San Diego',1223400),
array('Dallas',1188580),
array('San Antonio',1144646),
array('Detroit',951270)
);
我想按人口數量的順序對這些信息進行排序。 但是,當我嘗試使用arsort函數時,它按鍵數據而不是值數據(即按城市排序)對數組進行排序。
因此,我的問題是如何針對這種類型的多維數組編程編程按人口規模排序? 有任何想法嗎?
如果數組是這樣重寫的
$usapopstats = array(
'New York'=>8008278,
'Los Angeles'=>3694820,
'Chicago'=>2896016,
'Houston'=>1953631,
'Philadelphia'=>1517550,
'Phoenix'=>1321045,
'San Diego'=>1223400,
'Dallas'=>1188580,
'San Antonio'=>1144646,
'Detroit'=>951270
);
asort($usapopstats);
這將按總體大小對數組進行排序。
您需要創建一個用戶排序功能(這是最漂亮,編程最快的解決方案:
$usapopstats = array(
array('New York',8008278),
array('Los Angeles',3694820),
array('Chicago',2896016),
array('Houston',1953631),
array('Philadelphia',1517550),
array('Phonenix',1321045),
array('San Diego',1223400),
array('Dallas',1188580),
array('San Antonio',1144646),
array('Detroit',951270)
);
function sort_helper ($a, $b) {
if ($a[1] > $b[1]) return 1;
if ($a[1] == $b[1]) return 0;
return -1;
}
usort ($usapopstats, sort_helper);
var_dump($usapopstats);
這不是最快的代碼,適合說多達1000條記錄的列表,但我不會對具有100,000個條目的數組執行此操作。 對於每個比較,都將調用sort_helper函數,並且由於必須進行n log n個比較,因此這意味着要調用的函數數量也就一樣多。
如果需要此列表,請在密鑰中編碼總體,然后進行ksort:
$usapopstats = array(
array('New York',8008278),
array('Los Angeles',3694820),
array('Chicago',2896016),
array('Houston',1953631),
array('Philadelphia',1517550),
array('Phonenix',1321045),
array('San Diego',1223400),
array('Dallas',1188580),
array('San Antonio',1144646),
array('Detroit',951270)
);
$statshelper = array();
foreach($usapopstats as $index=>$stat){
$statshelper[$stat[1]."_".$index] = $stat; //also add the index to the key to avoid duplicates
}
ksort($statshelper, SORT_NUMERIC); //because the keys are strings (they contain an underscore) by default it will compare lexographically. The flag enforces numerical comparison on the part that can be converted to a number (i.e. the population)
$usapopstats = array_values($statshelper);
var_dump($usapopstats);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.