简体   繁体   English

PHP带有链接的逗号分隔列表

[英]PHP Separate comma list with links

I have a MySQL field called "tags" an example result. 我有一个名为“ tags”的MySQL字段,结果示例。 The single field has a list of text with comma separated values. 单个字段包含带有逗号分隔值的文本列表。

A real example: 一个真实的例子:

red, pants, shoes, heels, lookbook

I want to somehow use find and replace or implode feature to print out this row as separate links. 我想以某种方式使用查找和替换或内爆功能将这一行打印为单独的链接。

My guess so far: 到目前为止,我的猜测是:

<?php
$tag=$row["tags"];
whilst (!$tag=="") { 
echo '<a href="/tags/$tag">$tag</a>, "';
}
?>
  1. split the comma separated list into an array using explode() 使用explode()将逗号分隔的列表拆分为一个数组
  2. convert each element in the list to a link using foreach 使用foreach将列表中的每个元素转换为链接
  3. convert the array to a comma separated list using implode() 使用implode()将数组转换为逗号分隔的列表

example: 例:

$tags = explode(", ", $row["tags"]);
foreach ($tags as &$tag) {
    $tag = "<a href=\"/tags/$tag\">$tag</a>";
}
echo implode(", ", $tags);

Another approach would be using preg_replace : 另一种方法是使用preg_replace

$row['tags'] = "banana, apple, peach, strawberry";
echo preg_replace( '#([^,\s]+)#is', 
       '<a href="/tags/$1">$1</a>', 
       $row['tags']); 

You should probably take a look at this answer first SQL Array Search (how to store such an information in the database). 您可能应该首先看一下这个答案,即SQL Array Search (如何在数据库中存储这样的信息)。 If you still want to use coma separated list, the best way is probably using explode() , array_map() and implode() : 如果仍然要使用array_map()分隔列表,最好的方法可能是使用explode()array_map()implode()

function generateLink( $tag){
    $tag = htmlspecialchars( trim( $tag));
    $str = "<a href=\"/tags/$tag\">$tag</a>";
}

$tags = explode( ',', $row['tags']);
$new_tags = array_map( 'generateLink', $tags);
echo implode( ', ', $new_tags);

// Of course you can chain it to:
echo implode( ', ', array_map( 'generateLink', explode( ',', $row['tags'])));

However if you use correct database design you should this SELECT (displaying one product): 但是,如果使用正确的数据库设计,则应执行以下SELECT (显示一种产品):

SELECT tags.name
FROM tags_products
INNER JOIN tags ON tags_products.tag_id = tags.id
WHERE tags_products,product_id = ?

And with php: 与PHP:

$q = $db->query( 'mentioned select');
$result = array();
while( $row = $q->fetch_assoc()){
    $result[] = genereateLink( $row['name']);
}

And in case of mass listing of product to increase performance use this select with GROUP_CONCAT : 如果要大量列出产品以提高性能,请使用GROUP_CONCAT选择:

SELECT products.id, products.name, GROUP_CONCAT(tags.name ASC SEPARATOR ', ') AS tags
FROM products
LEFT JOIN tags_products ON tags_producsts.product_id = products.id
INNER JOIN tags ON tags_products.tag_id = tags.id
GROUP BY products.id

And apply the first mentioned code on $row['tags'] :) 并在$row['tags']上应用第一个提到的代码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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