我有一个数组从查询返回,但我想将其更改为另一个数据库查询的字符串
$test = $go->get_stuff();
$test = array(
'ONE',
'TWO',
'THREE',
'FOUR'
)
// expected outcome
$sql .= "(table.col IN ('ONE', 'TWO', 'THREE', 'FOUR') OR table.col IS NULL)";
答案 0 :(得分:2)
使用implode()
但同时也要确保前缀和附加单引号:
$string = "'" . implode("','", $test) . "'";
// 'ONE', 'TWO', 'THREE', 'FOUR'
答案 1 :(得分:1)
此问题已在此处得到解答:How to convert array to a string using methods other than JSON?
基本上,您需要使用implode function作为数据集。
$test = $go->get_stuff();
$test = array(
'ONE',
'TWO',
'THREE',
'FOUR'
)
// Implode array to string
$string = "'" . implode("','", $test) . "'";
// Deliver desired output
$sql .= "(table.col IN (".$string.") OR table.col IS NULL)";
答案 2 :(得分:0)
内爆数组:
$str = "'" . implode("', '", $test) . "'";
然后你可以将它添加到你的SQL:
$sql .= "(table.col IN ($str) OR table.col IS NULL)";
答案 3 :(得分:0)
使用implode()
。试试这个..
$in = "'".implode("','", $test)."'";
$sql .= "(table.col IN (".$in.") OR table.col IS NULL)";
答案 4 :(得分:0)
另一种方式是foreach和rtrim:
foreach($test as $v) { $str .= "'$v',"; } $str = rtrim($str, ',');
答案 5 :(得分:0)
你可以用“内爆”功能来做到这一点。
试试这个:
$test = $go->get_stuff();
$test = array(
'ONE',
'TWO',
'THREE',
'FOUR'
)
// expected outcome
$sql .= "(table.col IN ('".implode("','", $test)."') OR table.col IS NULL)";