我有一个公司文件夹目录,每个文件夹都根据公司缩写命名。我正在使用 php
制作一个表,该表创建一个 checkbox
、目录的 href
,然后是公司名称(它从中提取) SQL
)。
有没有一种方法可以根据从 SQL
中提取的完整公司名称(而不是文件夹名称)按字母顺序对表进行排序。例如,在我的图像中,“United Stationers”按字母顺序排列在其他两个的下方,但事实并非如此,因为文件夹名称按字母顺序排列在第一位。
这是我的 PHP
代码:
$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>\n");
echo ("<TR><TH>Manufacturer's Name</TH></TR>\n");
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>\n");}}
echo("</TABLE>\n");
最佳答案
填充 $longNames 数组后,您可以使用回调函数对 dirArray 进行排序。在 for 循环之前添加此内容:
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);
});
参见http://php.net/manual/en/function.usort.php有关 usort 函数的更多信息。
编辑:修复了代码中的语法错误。
关于php - 在 PHP 制作的 HTML 表中按字母顺序对 SQL 数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871808/