php - 如何从MySQL表行中选择唯一的数组?

标签 php mysql arrays

我有一个有 20 行的表,其中一行有例如:

2,3,5,6,8,22
2,3,5,6,8,22,44,55
etc.

如何从 mysql 表行中仅选择唯一的数字,而不是重复的,因此结果是:

2,3,5,6,8,22,44,55

表定义:

CREATE TABLE IF NOT EXISTS `test` (

  `id` int(11) NOT NULL auto_increment,

  `active` tinyint(1) NOT NULL default '1',

  `facilities` varchar(50) NOT NULL,

  PRIMARY KEY  (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

INSERT INTO `test` (`id`, `active`, `facilities`) VALUES

(1, 1, '1,3,5,6,7,8'),

(2, 1, '2,3,4,5,8,9'),

(3, 1, '4,5,6,7,9,10');

这是我的尝试:

SELECT DISTINCT facilities FROM test WHERE active='1'

$dbgeneral= explode(',', $row['facilities']);


$facilities = array(

"Air Conditioning" => "2",

"Balcony" => "4");

foreach ($facilities as $facilities=> $v) {

     if(in_array($v,$dbgeneral)) {

echo '';

}
}

最佳答案

由于这只是一个字段,您可以执行以下操作:

$result = mysql_query('SELECT facilities FROM table');

$facilities = array();

while(($row = mysql_fetch_array($result))) {
    $facilities = array_merge($facilities , explode(',', $row[0]));
}

$facilities = array_unique($facilities);

但是你应该考虑改变你的数据库设计,看起来你的数据没有标准化。

引用:explode() , array_merge() , array_unique()


根据您想要执行的查询类型,更好的表格布局是:

 | id  | facility |
 |  2  | 1        |
 |  2  | 2        |
 |  2  | 3        |
 ...
 |  3  | 1        |
 |  3  | 7        |
 |  3  | 9        |
 ...

然后然后你可以这样做:

SELECT DISTINCT facility FROM ...

关于php - 如何从MySQL表行中选择唯一的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417414/

相关文章:

mysql - 如何计算内部连接表中的行数

mysql - 对结果集执行 Post SQL 查询?

php - 从一个数组中减去另一个数组

javascript - 通过子数组处理数组

ios - 从 NSData 对象在 Swift 中创建一个数组

php - 将鼠标悬停在弹出窗口中显示名称 anchor 的内容,而不是单击以转到内容

php - 为什么 fetchArray 不直接应用 htmlspecialchars ?

PHP: 查找两个日期之间的天差 ("YmdHis") 返回

php - 通过 Cron 调用函数在其中做很多事情的解决方案?

PHP 的 exec() 没有为 FFmpeg 执行命令