Reputation: 942
I've got this : Table that has products and each product has more than 1 color for example :
I want to get only the colors only once, but with the bellow code I receive different arrays for each product.. array_merge somehow doesn't merge all arrays in one array.. Please help me to:
$query='SELECT GROUP_CONCAT(DISTINCT colors SEPARATOR ", ") FROM products WHERE colors!="" GROUP BY colors';
$result=mysql_query($query) or die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$num_rows=mysql_num_rows($result);
if($num_rows){
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$array = array($row[0]);
$colors = array_merge($array);
var_dump($colors );
}
Upvotes: 0
Views: 150
Reputation: 3333
If I understood your question correctly, meaning you want single array consisting of all colours that are in all items and this array has to be unique, you should do the following: you should declare $colors
out of while loop, and then replace array_merge
with function that checks if provided colour is in $colors
array, and if not then add to it. Code is below:
$query='SELECT GROUP_CONCAT(DISTINCT colors SEPARATOR ", ") FROM products WHERE colors!="" GROUP BY colors';
$result=mysql_query($query) or die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$num_rows=mysql_num_rows($result);
$colors=array();
if($num_rows){
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$array = array($row[0]);
$colors = array_merge($array);
}
$colors=array_unique($input);
var_dump($colors);
Upvotes: 0
Reputation: 3696
Do you just want an array of colors with no regard to products? Try this:
SELECT DISTINCT colors FROM products WHERE colors != ''
I'm guessing here, but I think your colors columns is just a comma separated list of colors. This is not really the best way to do such a thing but anyway... try the above query, then in php
$result=mysql_query($query) or die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$num_rows=mysql_num_rows($result);
if($num_rows){
$colors = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$array = explode(',' $row[0]); // your row is just a string, explode it to get an array
$colors = array_merge($colors, $array); // merge that into the colors array
}
$colors = array_map('trim', $colors); // in case there was any whitespace in your color strings
$colors = array_filter($colors); // remove any empties
$colors = array_unique($colors); // strip out the dupes
Upvotes: 1
Reputation: 160883
$query='SELECT DISTINCT colors FROM products WHERE colors !=""';
$result=mysql_query($query) or die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$colors = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$colors[] = $row[0];
}
var_dump($colors);
Upvotes: 0
Reputation: 9012
Don't CONCAT the colors but rewrite the SQL in a way you get a row for each color. Add them all in an array and run array_filter()
afterwards.
Upvotes: 0