dongqindan4406 2017-07-04 13:47
浏览 128

从数组php获取唯一值

I want to display only unique strings and I have this code:

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

I have put an array_unique like this:

$array = array_unique($array); 

But it returns this:

word-word
word
word2
word3
word-word

It doesn't print only unique values. What is wrong?

  • 写回答

3条回答 默认 最新

  • doudao1922 2017-07-04 14:07
    关注
    1. Explode your string.
    2. Trim outer spaces from each element.
    3. Replace inner spaces with hyphen in each element.
    4. Only keep non-empty elements.
    5. Only keep unique elements (using double array_flip).
    6. Display results.

    Code: (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>";
        }
    }
    


    Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch. This will remove the potentially unnecessary trailing
    from final element:

    Code:

    $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));
    

    Output:

    <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>
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本