[英]Why is array_unique not working in this situation
I have a column that contain integer values. 我有一列包含整数值。 I join all columns by doing
我通过这样做来加入所有列
"SELECT GROUP_CONCAT(column) AS column"
Then I build an array doing 然后我建立一个数组
while ($row = $result->fetch_assoc()){
$employees[] = $row['column'];
}
print_r($employees) returns Array ( [0] => 1,2,3,4,68,25,1 ) print_r($ employees)返回Array([0] => 1,2,3,4,68,25,1)
So I want to remove the duplicate 1 and for that I use array_unique
所以我想删除重复的1,为此我使用
array_unique
print_r(array_unique($employees));
This still brings back Array ( [0] => 1,2,3,4,68,25,1 ) 这仍然会带回Array([0] => 1,2,3,4,68,25,1)
What am I doing wrong here 我在这里做错了什么
Solution at SQL side: SQL端的解决方案:
SELECT GROUP_CONCAT(DISTINCT column) AS column
if you want an ordered list: 如果要订购清单:
SELECT DISTINCT column ORDER BY Column
and then store all rows by 然后将所有行按
while(...) $employees[] = $row['column'];
The problem is that you are trying to use array_unique()
on a string, which won't really do anything. 问题是您试图在字符串上使用
array_unique()
,但实际上不会做任何事情。
You can break this string into an array by using the explode()
function. 您可以使用
explode()
函数将此字符串分成数组。
$unique = array_unique(explode(',', $employees[0]);
Alternatively, you could just check inside your loop if a value has already been put into an array using in_array()
. 另外,您可以只在循环内部检查是否已使用
in_array()
将值放入数组中。
while ($row = $result->fetch_assoc()){
if(!in_array($row['column'], $employees)) {
$employees[] = $row['column'];
}
}
Just use the array_map
function. 只需使用
array_map
函数。 And map all value with intdiv
function 并使用
intdiv
函数映射所有值
$employees = array_unique(array_map("intdiv", $employees));
print_r($employees);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.