dongzhu7329 2015-06-16 07:24
浏览 63
已采纳

在PHP制作的HTML表中按字母顺序排序SQL数据

I have a directory of company folders, and each folder is named according to a company abbreviation. I am using php to make a table which creates a checkbox, a href to the directory, and then the company name (which it pulls from SQL).

Is there a way to alphabetically order the table based on the full company name pulled from SQL rather than the name of the folder. For example, in my image, 'United Stationers' would be below the other two alphabetically, but it isn't because the folder name comes first alphabetically.

The Table

Here's my PHP code:

$dir = "/var/files/companies/";
$myDirectory = opendir($dir);

$blacklist = array("Review");

while(false !== ($entryName = readdir($myDirectory))) {
    if (!in_array($entryName, $blacklist)) {
        $dirArray[] = $entryName;}}

closedir($myDirectory);
sort($dirArray);
$indexCount = count($dirArray);

//new array here for matching short/long names
$longNames=array();

$con = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());

$query = "Select comp_id, short_name FROM database where vid=2";

if ($stmt = $con->prepare($query)) {
    $stmt->execute();
    $stmt->bind_result($comp_id, $short_name);
    while ($stmt->fetch()) {
        $longNames[strtolower($comp_id)]=$short_name;}
    $stmt->close();}

echo ("<TABLE border=1 cellpadding=5 cellspacing=0 class= whitelinks>
");
echo ("<TR><TH>Manufacturer's Name</TH></TR>
");

for ($index=0; $index < $indexCount; $index++) {
    if (substr("$dirArray[$index]", 0, 1) != ".") {
        echo("<td>");
        echo("<input type=\"checkbox\" name=\"comp[]\" value= '$dirArray[$index]' </a>");
        echo(" ");
        echo("<a href='/master/$dirArray[$index]'\>$dirArray[$index]</a>");
        echo("- ");
        if (array_key_exists($dirArray[$index], $longNames)){
            $short = ($longNames[$dirArray[$index]]);
            echo($short); }
        echo("</td>");
        echo("</TR>
");}}

echo("</TABLE>
");

展开全部

  • 写回答

2条回答 默认 最新

  • dsz90288 2015-06-16 07:45
    关注

    You can sort the dirArray using a callback function once $longNames array is populated. Add this before your for loop:

    usort($dirArray, function($dir1, $dir2) use ($longNames) {
        $name1 = isset($longNames[$dir1]) ? $longNames[$dir1] : $dir1;
        $name2 = isset($longNames[$dir2]) ? $longNames[$dir2] : $dir2;
    
        return strcmp($name1, $name2);
    });
    

    See http://php.net/manual/en/function.usort.php for more info about usort function.

    EDIT: fixed syntax errors in code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部