search
Homephp教程php手册如何用PHP4进行自然排序

对于这样几个字串:

inf1
inf3
inf12

如果我们只是用strcmp()函数来做比较,得出的次序如下:

inf1
inf12
inf3

可这显然不是我们想要的结果,一般我们的解决方法是采用在数字前加一个0,如 inf01 inf03 inf12 这样。可不可以不用加这个0也能按自然次序(nature order)排出我们想要的真正的顺序呢?

在PHP4中提供了这样两个函数可以做到这一点:

int strnatcasecmp (string str1, string str2)
int strnatcmp(string str1, string str2)

它们支持的版本是:PHP4 >= 4.0RC2

说明如下:

按自然次序(nature order)对 str1 str2 进行排序。
返回值 返回值 =0 表示 str1 等于 str2,
返回值 >0 表示 str1 大于 str2。

例子如下:


$str=array("a","a0","a3","a2","a10","a18","a24");

$k=count($str);
echo "total=".$k."
";

echo "
用strnatcmp排序
";
for($i=1;$iif(strnatcmp($str[$i-1],$str[$i])>0){
$tmp=$str[$i-1];
$str[$i-1]=$str[$i];
$str[$i]=$tmp;
}
}

print_r($str);
echo "
用strcmp排序
";


for($i=1;$iif(strcmp($str[$i-1],$str[$i])>0){
$tmp=$str[$i-1];
$str[$i-1]=$str[$i];
$str[$i]=$tmp;
}
}

print_r($str);

echo "
用sort排序
";
sort($str);
print_r($str);
?>

输出如下:


total=7


用strnatcmp排序
Array ( [0] => a [1] => a0 [2] => a2 [3] => a3 [4] => a10 [5] => a18 [6] => a24 )
用strcmp排序
Array ( [0] => a [1] => a0 [2] => a2 [3] => a10 [4] => a18 [5] => a24 [6] => a3 )
用sort排序
Array ( [0] => a [1] => a0 [2] => a10 [3] => a18 [4] => a2 [5] => a24 [6] => a3 )


明白了吗?

其实这个函数也支持比较复杂一点的功能。如:

a
x2-g8
1.001
试一下吧,真得很有用。
Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools