gpt4 book ai didi

php - 如何在PHP中按最大相同值对数组进行排序

转载 作者:行者123 更新时间:2023-12-02 06:34:16 25 4
gpt4 key购买 nike

如何按最大相同值对数组进行排序??

这里是数组

Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 3
[4] => 3
[5] => 4
[6] => 4
[7] => 4
[8] => 4
[9] => 4
[10] => 5
)

我想要的是按最大值对数组进行排序,所以数组应该看起来

Array
(
[0] => 4
[1] => 4
[2] => 4
[3] => 4
[4] => 4
[5] => 2
[6] => 2
[7] => 2
[8] => 3
[9] => 3
[10] => 5
)

最佳答案

试试这个:

$arr = [3,4,2,3,2,2,3,4,5,2];

$count = [];
foreach ($arr as $a)
{
// Count how many times each number appears and store it in an array
// where the key is the number and the value the count.
$count[$a] = isset($count[$a]) ? $count[$a]+1 : 1;
}

// As @drip wrote you can use 'array_count_values' instead:
// $count = array_count_values($arr);

// Sort the array in reverse order while maintaining index association.
arsort($count);

$new = [];
foreach ($count as $a => $c)
{
// Create a new array with the values appearing as many times as counted.
for ($i = 0; $i < $c; $i++)
{
$new[] = $a;
}
}

关于php - 如何在PHP中按最大相同值对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com