【发布时间】:2015-12-30 22:32:43
【问题描述】:
我有一张这样的桌子:
// mytable
+----+---------+------------+
| id | id_post | code_table |
+----+---------+------------+
| 1 | 34523 | 1 |
| 2 | 3453 | 4 |
| 3 | 43434 | 2 |
| 4 | 54321 | 1 |
| 5 | NULL | NULL |
| 6 | 32411 | 2 |
| 7 | 42313 | 1 |
| 8 | 34242 | 2 |
+----+---------+------------+
// ^ all of my focus is on this column
我也有这个数组:
$convert_code_name = array (
"1" => "Post1",
"2" => "Post2",
"3" => "Post3",
"4" => "Post4"
);
现在我想创建这个:
$query = "select * from post1
union all
select * from post2
union all
select * from post4";
// there isn't "post3", because 3 isn't exist in the code_table column
我该怎么做?
这是我的尝试:
// connect to database
$stm = $db->prepare('select * from mytable');
$stm->execute();
$result = $stm->fetch();
/* array_unique: removes duplicate values
array_filter: removes "NULL" values */
array_filter(array_unique($result[code_table]), function($item) {
return $item != 'NULL';
});
foreach($item as $numb){
$query .= 'select * from'.$convert_code_name[$numb].'union all';
}
但我不知道为什么我的代码不起作用,我该怎么做?
【问题讨论】:
-
我想你只是想要一个
in列表。 -
array_filter返回一个新数组,你需要将它赋值给一个变量。 -
$result只包含表格的第一行。你的意思是使用fetchAll? -
@Barmar 老实说我不知道,也许我需要
fetchAll.. 我只是明白(到目前为止)最好使用DISTINCT(mysql 层)而不是@987654331 @(php层)