php - 在 MySQL 之后保留 PHP 排序

标签 php mysql

我正在构建一个结果页面,用于计算特定 ID 在数组中出现的次数。

我的代码对数组的指定元素执行 array_multisort:

      $colpubid = array_column($votedpubs, 'pubid');
      $colcount = array_column($votedpubs, 'count');
      array_multisort ( $colcount, SORT_DESC, $colpubid, SORT_ASC, $votedpubs );

当我在页面上显示此内容时,我得到以下信息:

PubIDCount

BES/262 4
BES/527 3
BES/572 2
BES/158 1
BES/167 1
BES/193 1
BES/238 1

但是,当我从 MySQL 数据库中查找相应元素时,顺序会被覆盖,结果现在根据从数据库检索的顺序进行排序。

Order after MySQL lookup

这是使用以下代码:

    while ($row3 = mysqli_fetch_array($pubidresult))
    {
       foreach($votedpubs as $thispub )
          {
            if ($row3['PubID'] == $thispub['pubid']) {
                echo "<tr><td>" . $thispub['pubid'] . "</td><td>" . $thispub['count'] . "</td><td>" . $row3['Name'] . "</td><td>" . $row3['Town'] . "</td></tr>\n";
            }
          }
    }

有没有办法我仍然可以执行 MySQL 查找以添加额外字段(名称和城镇),同时保持计数降序排序?

最佳答案

我能想到的解决方案是首先通过 pubID 对 $votedpubs 数组进行索引 (使用 array_column()),然后在数据库查询的 while() 循环中将详细信息添加到 $votedpubs 数组中。

$votedpubs = array_column($votedpubs, null, 'pubid');
while ($row3 = mysqli_fetch_array($pubidresult))
{
    $votedpubs[$row3['PubID']]['Name'] = $row3['Name'];
    $votedpubs[$row3['PubID']]['Town'] = $row3['Town'];
}

foreach ( $votedpubs as $thispub )  {
    echo "<tr><td>" . $thispub['pubid'] . "</td><td>" . $thispub['count'] . "</td><td>" . $thispub['Name'] . "</td><td>" . $thispub['Town'] . "</td></tr>\n";
}

关于php - 在 MySQL 之后保留 PHP 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53143778/

相关文章:

php - Composer require-dev 在不同的包中需要依赖 require-dev

php - 如何在 DOM 和 PHP 中获取文本节点?

php - php 和 mysql 上的阿拉伯字符 "???????"

php - 如何在 PHP 中设置时间/日期的格式?

mysql - 将数据从一个表传输到同一数据库中的另一个表

php - 处理完成后删除 URL 中的 GET 参数(不使用 POST),PHP

javascript - 从 url Jquery 中删除特定字符串

php - 与没有任何 'verb' 的 if 语句混淆(例如 ==、!= 等)

php - Laravel 中如何避免列名冲突?

macos - 无法从 PHP : "mysql_connect(): No such file or directory" 连接到 MySQL