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

不言
Release: 2023-04-04 09:20:02
forward
2530 people have browsed it

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)
Copy after login

Solution 2: Bubble method
1. Loop the outer layer i
2. Loop j in the inner layer, the judgment condition is j=i 1;j3. Replace arr[i in the inner layer ].arr[j] > 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));
}
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template