簡體   English   中英

為什么在這種情況下array_unique無法正常工作

[英]Why is array_unique not working in this situation

我有一列包含整數值。 我通過這樣做來加入所有列

"SELECT GROUP_CONCAT(column) AS column"

然后我建立一個數組

while ($row = $result->fetch_assoc()){
        $employees[] = $row['column'];
    }

print_r($ employees)返回Array([0] => 1,2,3,4,68,25,1)

所以我想刪除重復的1,為此我使用array_unique

print_r(array_unique($employees)); 

這仍然會帶回Array([0] => 1,2,3,4,68,25,1)

我在這里做錯了什么

SQL端的解決方案:

SELECT GROUP_CONCAT(DISTINCT column) AS column

如果要訂購清單:

SELECT DISTINCT column ORDER BY Column

然后將所有行按

while(...) $employees[] = $row['column'];

問題是您試圖在字符串上使用array_unique() ,但實際上不會做任何事情。

您可以使用explode()函數將此字符串分成數組。

$unique = array_unique(explode(',', $employees[0]);

另外,您可以只在循環內部檢查是否已使用in_array()將值放入數組中。

while ($row = $result->fetch_assoc()){
    if(!in_array($row['column'], $employees)) {
        $employees[] = $row['column'];
    }
}

只需使用array_map函數。 並使用intdiv函數映射所有值

$employees = array_unique(array_map("intdiv", $employees));
print_r($employees);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM