从foreach php中删除重复项

时间:2018-11-21 10:58:56

标签: php mysql

我已经尝试过array_unique,但是没有得到想要的结果。

这是数据库结构:

enter image description here

这是我尝试过的方法,但是两次获得相同的“用户1”应该是一个。

<div class="navWrapper">
  <nav id="flex-wrapper" class="flex-wrapper">
    <div class="top-row-logo" id="top-row-logo">
    <img class="logo-img" src="https://img1.wsimg.com/isteam/ip/7bf494f1-7493-4549-b272-842b0d021577/logo/345e441d-0495-4f5b-bd62-f6413ac9b7a5.png/:/rs=h:71" alt="Sino Medical Institute">
    </div>
    <div class="top-row-links">
      <ul class="navbar">
        <li>
          <a href="#">Home</a>
        </li>
        <li>
          <a href="#">About Us</a>
        </li>
        <li>
          <a href="#">Services</a>
        </li>
        <li>
          <a href="#">
            Register
          </a>
        </li>
        <li>
          <a href="#">Contact Us</a>
        </li>
        <li>
          <a href="#">FAQ</a>
        </li>
      </ul>
    </div>
    <div class="login-links">
      <ul>
        <li>
          <a href="#" class="login-button">Login</a>
        </li>
      </ul>
    </div>
  </nav>
</div>

以下是来自db的数据:

$stmt = $db_con->query("SELECT sender,recipient, content, sending_time
FROM messages AS sender
WHERE (sender='admin' OR recipient='admin')
GROUP BY sender,recipient
ORDER BY sending_time DESC
");

$stmt->execute();
foreach ($stmt as $key => $value) {

    if ($value['sender'] == 'admin') {
        $my = $value['recipient'];
    } else if ($value['recipient'] == 'admin') {
        $my = $value['sender'];
    } else {
        $my = $value['sender'];
    }
    if (!in_array($my, explode(' ', $my))) {
        echo '<a href="javascript:void(0)" class="list-group-item p10 b0 b-rad-0">
                    <div class="online-users pull-left mr5">
                        <img src="../uploads/userprofile/default/avatar.jpg" onerror="this.onerror=null;imgDefault(this);" alt="avatar" class="online-users-img">
                        <span title="online"></span>
                    </div>
                    <strong class="text-primary h4 mb2">' . $my . '<small class="pull-right">OCT 23</small></strong>
                    <div><small class="text-muted">asdasdajkasdhjgjhgjhgjhgjghjgjgggggggggggggsdfsdf...</small></div>
                </a>';

    }
}

1 个答案:

答案 0 :(得分:0)

//Find duplicates 

$arr_data = array( 
    'one', 
    'two', 
    'Three', 
    'Four', 
    'Five', 
    'Six', 
    'Seven', 
    'Eight', 
    'Nine' 
);
$unique_data = array_unique($arr_data); 
$dup= array_diff_key( $arr_data, $unique_data); 
array_count_values($dup);