【发布时间】:2021-09-21 17:13:45
【问题描述】:
正如标题所示,我想在 php 和 mysql 中按字母顺序列出(混合所有值)并按值对所有行的关键字进行排序。
我有多行列的名称为“关键字”,用逗号分隔:
-
voiture électrique,电池回收
-
Télétravail, travail à domicile, 局
-
réchauffement climatique, effet de serre
-
合作,出差
这是我的代码:
<?php
include_once ("config.php");
$query_top = "SELECT keywords FROM market WHERE keywords != ''";
if ($stmt_top = $bdd->prepare($query_top)) {
$stmt_top->execute();
$result_top = $stmt_top->get_result();
$num_of_rows_top = $result_top->num_rows;
$stmt_top->close();
}
while ($row_kw = $result_top->fetch_assoc())
{
$keywords = $row_kw['keywords'];
$array = array_filter(array_map('trim', explode(',', $keywords)));
sort($array);
$array = implode('<br>', $array);
echo $array . '<br/>';
}
?>
我的结果需要按字母顺序按值排序:
-
太棒了
-
美丽
-
联合办公
有什么想法吗?
编辑最终工作代码是:
$array = [];
while ($row_kw = $result_top->fetch_assoc())
{
$array = array_merge($array, explode(',', $row_kw['keywords']));
}
$array = array_filter(array_map('trim', $array));
sort($array);
// FR language
$collator = new Collator('fr_FR');
$collator->asort( $array );
$array = implode('<br>', $array);
echo $array . '<br/>';
非常感谢 @Kinglish 的帮助。
【问题讨论】:
-
以逗号分隔的格式存储数据是导致此类问题的基本设计错误
-
精确的@ADyson,例如从文本区域插入多行:
include_once ("config.php"); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $text = trim($_POST['keywords']); $textAr = explode(",", $text); $textAr = array_filter($textAr, 'trim'); // remove any extra \r chars foreach ($textAr as $line) { mysqli_query($bdd, "INSERT INTO keywords VALUES(NULL,'1','".$line."','4512452455','2021-07-12 17:30:23')") or die (mysqli_error($bdd)); } } -
好的,那么您是否要修复这个错误并使用带有外键的辅助表来存储关键字?
-
没错,但我会先尝试找到解决方案。 ;)
-
如果您先修复数据结构,您的问题的解决方案会容易得多……这就是我的观点。