猿问

如何在 PHP 中创建按字母顺序排列的下拉菜单

我正在尝试重新编写此代码,以便下拉菜单按字母顺序排列:


$activeProjectDropdown.="<option value=''>Select Project</option>";

$getInfo = "SELECT id, customer, job_name, haul_info 

            FROM dispatch_jobs 

            WHERE (:mydate BETWEEN delivery_date AND delivery_date_end) 

            ORDER BY customer, job_name";


$result=DB::run($getInfo, ['mydate' => $myDate]);

while($row=$result->fetch(PDO::FETCH_BOTH)) {

    if(!empty($row['haul_info'])) {

        $haulinfo = "($row[haul_info])";

    }else{

        $haulinfo = "";

    }


    if($checkit == $row['id']){

        $woot = 'selected=selected';

    }else{

        $woot = '';

    }


    $customerName = pdo_getName('name', 'customer', "$row[customer]");

    $activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$customerName $haulinfo</option>\n";

}

在此代码中,查询从数据库中返回一些行,其中 customer 是不按任何字母顺序排列的数字代码。在代码的更下方,调用了一个函数,该函数从表的pdo_getName列和 id 中获取并查询数据库,返回客户的字符串化名称。因为直到后来循环之后才检索到名称,所以我无法找出一种可以按字母顺序排列. 我尝试将and 下拉代码放入关联数组中,然后按namecustomer$row['customer']$activeProjectDropdown$customerName$customerName并将所有内容连接成一个字符串,但这不起作用,因为有重复的键。在同一条路径上,我可能有一个嵌套数组,但我认为必须有一个更简单的解决方案我错过了。谢谢您的帮助!


慕村9548890
浏览 118回答 2
2回答

阿晨1998

编写一个 JOIN 查询并在一个查询中获取所有数据,然后您可以按照我认为您要求的方式对客户名称进行排序。这将提高性能并简化代码。$getInfo = "SELECT dj.id, dj.customer, dj.job_name, dj.haul_info&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FROM dispatch_jobs dj&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LEFT JOIN customer c ON c.id = dj.customer&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WHERE (:mydate BETWEEN dj.delivery_date AND dj.delivery_date_end)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ORDER BY c.name, dj.job_name";$result=DB::run($getInfo, ['mydate' => $myDate]);while($row=$result->fetch(PDO::FETCH_BOTH)) {&nbsp; &nbsp; if(!empty($row['haul_info'])) {&nbsp; &nbsp; &nbsp; &nbsp; $haulinfo = "($row[haul_info])";&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $haulinfo = "";&nbsp; &nbsp; }&nbsp; &nbsp; if($checkit == $row['id']){&nbsp; &nbsp; &nbsp; &nbsp; $woot = 'selected=selected';&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $woot = '';&nbsp; &nbsp; }&nbsp; &nbsp; $activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$row[name] $haulinfo</option>\n";}

德玛西亚99

尝试这个:SELECT&nbsp;...&nbsp;ORDER&nbsp;BY&nbsp;customer&nbsp;ASC,&nbsp;job_name这首先按客户(升序)对所有内容进行排序,然后在两行或更多行的客户字段相等时按作业名称(升序,这是默认值)对所有内容进行排序。更多信息在这里
随时随地看视频慕课网APP
我要回答