比较php中的各种比较函数
通过简单的代码,比较php中sort,natsort和usort的不同。
<html> <head> <style type="text/css"> li{ border:2px solid black; padding: 0.5em; width: auto; margin: 0.5em; } p{ font-size: 20px; color: blue; } ol li{ border: 1px solid red; margin: 0px; } </style> </head> <body> <h3>My First Hello World in PHP</h3> <?php $dateFile = fopen("info.txt", "r"); while ($dateLine = fgets($dateFile, 4096)) { $dateList[] = $dateLine; } echo "<ul>"; echo "<li><p>Sorting the dates using sort() function:</p><ol>"; sort($dateList); foreach ($dateList as $date) { echo "<li>$date</li>"; } echo "</ol></li>"; echo "<li><p>Sorting the dates using natsort() function:</p><ol>"; natsort($dateList); foreach ($dateList as $date) { echo "<li>$date</li>"; } echo "</ol></li>"; function opDateSort($a, $b) { if ($a == $b) return 0; list($aMonth, $aDay, $aYear) = explode("-", $a); list($bMonth, $bDay, $bYear) = explode("-", $b); $aMonth = str_pad($aMonth, 2, "0", STR_PAD_LEFT); $bMonth = str_pad($bMonth, 2, "0", STR_PAD_LEFT); $aDay = str_pad($aDay, 2, "0", STR_PAD_LEFT); $bDay = str_pad($bDay, 2, "0", STR_PAD_LEFT); $aDate = $aYear.$aMonth.$aDay; $bDate = $bYear.$bMonth.$bDay; return $aDate>$bDate?1:-1; } echo "<li><p>Sorting the dates using usort() with user defined comparing function:</p><ol>"; usort($dateList, ‘opDateSort‘); foreach ($dateList as $date) { echo "<li>$date</li>"; } echo "</ol></li>"; echo "</ul>"; ?> </body> </html>
其中info.txt的内容为
4-1-1969 10-25-1987 9-11-1982 6-18-1928 4-27-1927 6-12-1923 7-16-1922 7-23-1921
结果如图所示
本文出自 “Accplayer的小地方” 博客,请务必保留此出处http://accplaystation.blog.51cto.com/9917407/1613529
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。