seankonig
seankonig

Reputation: 53

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 )

So I want to remove the duplicate 1 and for that I use array_unique

print_r(array_unique($employees)); 

This still brings back Array ( [0] => 1,2,3,4,68,25,1 )

What am I doing wrong here

Upvotes: 0

Views: 202

Answers (3)

Pascal Tovohery
Pascal Tovohery

Reputation: 986

Just use the array_map function. And map all value with intdiv function

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

Upvotes: 0

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

The problem is that you are trying to use array_unique() on a string, which won't really do anything.

You can break this string into an array by using the explode() function.

$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().

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

Upvotes: 0

Wiimm
Wiimm

Reputation: 3615

Solution at SQL side:

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'];

Upvotes: 2

Related Questions