简体   繁体   中英

List and sort keywords by value alphabetically php mysql

As the title suggests i want to list (mix all the values) and sort keywords of all rows by value alphabetically in php and mysql.

I have multiple rows with the column's name "keywords", separated with commas :

  • voiture électrique, recyclage des batteries

  • Télétravail, travail à domicile, bureau

  • réchauffement climatique, effet de serre

  • coworking, travail

Here is my code :

<?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/>';

}

?>

My result need to be sort by value alphabetically like :

  • Awesome

  • Beauty

  • Coworking

Any ideas?

EDIT FINAL WORKING CODE IS :

$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/>';

Thanx a lot to @Kinglish for the help.

Sort your array outside the loop that is building it

$array=[];
while ($row_kw = $result_top->fetch_assoc()) {
  array_merge($array, explode(',', $row_kw['keywords']);
}
$array = array_filter(array_map('trim', $array));
sort($array);
$array = implode('<br>', $array);
echo $array . '<br/>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM