我有一個已經排序的數組。Prepend到數組,但保留索引與PHP
現在我想採取所有有一個子數組值爲0的數組,並把它們放在數組的開始。
這就是我試圖做的:
foreach($dealStatsArray as $deal_id => $dealStats)
{
if($dealStats['revenueY'] == 0)
{
$tmpArray[$deal_id] = $dealStats; // Store the array
unset($dealStatsArray[$deal_id]); // Unset the current one, since it is not in right position
array_unshift($dealStatsArray, $tmpArray); // Prepend the tmp array, to have it at the beginning of the array
}
}
現在的問題是,array_unshift()的作用:
「所有的數字鍵名將修改爲從零開始計數」 -php net array_unshift()
這弄亂了我得到的代碼的其餘部分,因爲我需要保留$ dealStatsArray上的索引,並且新的前綴數組的索引應該是$ deal_id而不是0.
我該怎麼做?我需要一個可以管理前面加上2〜3次到數組的開頭,就像它正常工作與array_push溶液(追加)我想這樣做,只是前面加上
更新:這裏是我目前uasort功能,被排序revenueY值後的數組,所以最多是在數組的開始,然後降..
function cmp($a, $b)
{
if (($a["revenueY"]) == ($b["revenueY"])) {
return 0;
}
return (($a["revenueY"]) > ($b["revenueY"])) ? -1 : 1;
}
uasort($dealStatsArray, "cmp");
現在,如果我跟着@ thaJeztah的答案,這在一定程度作品,然後我在下面添加了這個:
function sortbyRevenueY($a, $b) {
if ($a['revenueY'] == $b['revenueY']) {
return 0;
}
return ($a['revenueY'] == 0) ? -1 : 1;
}
uasort($dealStatsArray, 'sortbyRevenueY');
但是這並不正確,它確實需要所有的收益== ==數組,並且在數組的開頭預先計算,但是其餘的數組會得到未分類(從最高到最低,第一個uasort())
這是我的最終目標:要有一個數組,其中所有revenueY == 0都位於數組的開始位置,在這之後,最高收入將在數組末尾處下降,然後下降到最低收入。
請給出一個或兩個現有數組的示例,新元素的索引和預期輸出。 – mario 2013-03-18 23:38:46
你如何想象這種工作?如果我有一個看起來像這樣的數組(array)(0 =>'a',1 =>'b')'你會「預先」做什麼?覆蓋值爲0?在-1處插入一些東西? – ITroubs 2013-03-18 23:43:13
@ITURBBS'關聯'數組可以在保持其鍵/值關係的同時進行排序。即有一個數組'array(2 =>'c',1 =>'b',0 =>'a')'應該是可能的 – thaJeztah 2013-03-18 23:59:38