我有一个已经排序的数组。
现在我想取所有子数组值为 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 函数,它在收入 Y 值之后对数组进行排序,以便最高数字在数组的开头,然后降序..
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');
但这不正确,它确实需要所有的收入 Y==0 数组并在数组的开头添加,但是其余的数组未排序(从最高到最低,第一个 uasort())
这是我的最终目标:拥有一个数组,其中所有的收入 Y==0 都在数组的开头,在这些之后,最高收入紧随其后,然后下降到数组末尾的最低收入。