Php 将数字从高转换为低

Php 将数字从高转换为低,php,Php,我们正试图重新排列号码 比如说 5695479 to 9976554 48932 to 98432 表示所有较大的数字,然后是较小的数字。 我在搜索php中的一些内置函数,我们发现排序函数可以使用数组 $numbers=array(4,6,2,22,11); sort($numbers); function my_sort($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } $a=array

我们正试图重新排列号码 比如说

        5695479  to 9976554
        48932  to 98432
表示所有较大的数字,然后是较小的数字。 我在搜索php中的一些内置函数,我们发现排序函数可以使用数组

$numbers=array(4,6,2,22,11);
sort($numbers);


function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}

$a=array(4,2,8,6);
usort($a,"my_sort");
$numbers=数组(4,6,2,22,11);
排序(数字);
函数my_sort($a,$b)
{
如果($a==$b)返回0;

return($a此函数没有特定的内置函数。但是,您可以使用多个内置函数来完成任务

  • 您可以使用
    strval
    将整数转换为字符串
  • 现在,将字符串按每个数字拆分,得到一个整数数组
  • 应用
    rsort()
    将它们按降序排序
  • 内爆()
    将它们放回,以获得您想要的号码
片段:

<?php

$str = strval(5695479);
$nums = str_split($str);
rsort($nums);
echo implode("",$nums);
<?php

$num = 48932; // if number is in string format, loop char by char using for loop
$count = [];

while($num > 0){
     if(!isset($count[$num % 10])) $count[$num % 10] = 0;
    $count[$num % 10]++;
    $num = intval($num / 10);
}

$new_num = 0;
for($i = 9; $i >=0; --$i){
  if(!isset($count[$i])) continue;
  while($count[$i]-- > 0) $new_num = $new_num * 10 + $i; // you would rather concatenate here incase of string. 
}

echo $new_num;

我不认为你会发现任何内置于php中的东西会像那样进行非常特殊的奇数排序。你必须创建自己的代码来处理不同的情况,以便对数组中的内容进行排序(一个条件来检查它是否在某个范围内,然后根据它排序/添加/重建数组)。