我正在构建一个结果页面,用于计算特定 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 数据库中查找相应元素时,顺序会被覆盖,结果现在根据从数据库检索的顺序进行排序。
这是使用以下代码:
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/