我无法删除数组中的重复项


I can not remove duplicates in array

我有这个:包含产品的表,并且每个产品具有 1 种以上的颜色,例如:

  1. 玻璃有红色、绿色
  2. 球有红色,绿色,黄色

只想只获取一次颜色,但是使用波纹管代码,我为每个产品收到不同的数组..array_merge不知何故不会将所有数组合并到一个数组中。请帮助我:

  1. 将数组合并为一个
  2. 删除新数组中的配音颜色。
$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 ); 
}

您是否只想要一系列颜色而不考虑产品?试试这个:

SELECT DISTINCT colors FROM products WHERE colors != ''

我在这里猜测,但我认为您的颜色列只是一个逗号分隔的颜色列表。这不是做这样的事情的最好方法,但无论如何......尝试上面的查询,然后在 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

不要控制颜色,而是重写 SQL,以便为每种颜色获得一行。将它们全部添加到一个数组中,然后运行array_filter()

$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); 

如果我正确理解了您的问题,这意味着您想要由所有项目中的所有颜色组成的单个数组,并且该数组必须是唯一的,您应该执行以下操作: 您应该声明 $colors out of while 循环,然后将array_merge替换为检查提供的颜色是否在数组$colors函数, 如果没有,那就添加它。代码如下:

$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);