通过简单的代码,比较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> <h4>My First Hello World in PHP</h4> <?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
结果如图所示
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。