我想只显示唯一的字符串,我有这段代码:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
$array = array_unique($array);
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
}
}
我已经像这样array_unique
:
$array = array_unique($array);
但它返回了这个:
word-word
word
word2
word3
word-word
它不会仅打印唯一值。有什么问题?
答案 0 :(得分:0)
代码:(Demo)
while($rez=$result->fetch_assoc()) {
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){$clean[]=$v;} // retain non-empty values
}
$clean=array_flip(array_flip($clean)); // double flip is faster than array_unique
foreach($clean as $v){
echo "<a href=\"http://example.com/$v\">$v</a><br>";
}
}
或者,您可以在第一个foreach循环中执行所有value和html prep,然后使用implode显示批处理。这将从最终元素中删除潜在的不必要的尾随:
代码:
$rez['tags']=' , word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){
$clean[]="<a href=\"http://example.com/$v\">$v</a>"; // prep non-empty values for display
}
}
echo implode("<br>",array_unique($clean));
输出:
<a href="http://example.com/word">word</a><br>
<a href="http://example.com/word-word">word-word</a><br>
<a href="http://example.com/word2">word2</a><br>
<a href="http://example.com/word3">word3</a>
答案 1 :(得分:0)
认为问题是因为在 array_unique
操作之后而不是之前处理字符串。请尝试以下方法:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
}
$array = array_unique($array);
foreach ($array as $value) {
echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
}
}
答案 2 :(得分:0)
我已经解决了,我会发布代码可能对某人有好处!
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$alltags=array();
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $key => $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
$alltags[]=$value;
}
}
$array=array_unique($alltags);
foreach ($array as $value) {
echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
}