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;j
<?php function customComp($a,$b){ return intval($a.''.$b) > intval($b.''.$a); } //解法1:自定义排序 function PrintMinNumber($numbers) { usort($numbers,'customComp'); return intval(implode('',$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].''.$arr[$j])>intval($arr[$j].''.$arr[$i])){ $temp=$arr[$i]; $arr[$i]=$arr[$j]; $arr[$j]=$temp; } } } return intval(implode('',$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!