您好,登錄后才能下訂單哦!
通過簡單的代碼,比較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的內(nèi)容為
4-1-1969 10-25-1987 9-11-1982 6-18-1928 4-27-1927 6-12-1923 7-16-1922 7-23-1921
結(jié)果如圖所示
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。