Home >Backend Development >PHP Tutorial >How to arrange the array into the smallest number in php (code attached)

How to arrange the array into the smallest number in php (code attached)

不言
不言forward
2018-10-10 11:22:162552browse

The content of this article is about how to arrange the array into the smallest number in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Input an array of positive integers, concatenate all the numbers in the array to form a number, and print the smallest number among all the numbers that can be concatenated. For example, if you input the array {3, 32, 321}, the smallest number that these three numbers can be printed out is 321323.
Solution 1
1. Array sorting, using custom sorting rules is a.b>b.a a and b exchange positions
2.Using the usort function

function costomcomp(a,b)
    return a.b > b.a
usort(arr,'costomcomp')
return implode('',arr)

Solution 2: Bubble method
1. Loop the outer layer i
2. Loop j in the inner layer, the judgment condition is j=i 1;j2faf514f1916b423f39ec41a7cbf77fd arr[j].arr[i] Swap position

<?php
function customComp($a,$b){
        return intval($a.&#39;&#39;.$b) > intval($b.&#39;&#39;.$a);
}
//解法1:自定义排序
function PrintMinNumber($numbers)
{
        usort($numbers,&#39;customComp&#39;);
        return intval(implode(&#39;&#39;,$numbers));
}
$arr=array(3,32,321);
$result=PrintMinNumber($arr);
var_dump($result);

$result=PrintMinNumber2($arr);
var_dump($result);

//解法2:冒泡排序
function PrintMinNumber2($arr)
{
        $length=count($arr);
        for($i=0;$i<$length;$i++){
                for($j=$i+1;$j<$length;$j++){
                        if(intval($arr[$i].&#39;&#39;.$arr[$j])>intval($arr[$j].&#39;&#39;.$arr[$i])){
                                $temp=$arr[$i];
                                $arr[$i]=$arr[$j];
                                $arr[$j]=$temp;
                        }   
                }   
        }   
        return intval(implode(&#39;&#39;,$arr));
}

The above is the detailed content of How to arrange the array into the smallest number in php (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete