【问题标题】:PHP Change array to string [duplicate]PHP将数组更改为字符串[重复]
【发布时间】:2014-10-02 14:34:51
【问题描述】:

我有一个从查询返回的数组,但我想将它更改为另一个数据库查询的字符串

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

【问题讨论】:

  • 拜托,拜托,拜托:使用准备好的陈述。不要只是将查询串在一起:注入非常真实,非常普遍
  • 听起来您真正想要的是将两个表连接在一起 - 取消查询,获取数组,然后在该数组上运行另一个查询 - 只需在 SQL 中使用 JOIN。跨度>
  • 在我看来你可以在这里使用JOIN 而不是创建两个查询?
  • 这是一场等待发生的意外。正如其他人已经指出的那样;准备您的查询。不要只是公然将文本直接放入您的查询中。

标签: php arrays string


【解决方案1】:

使用implode(),但也要确保在前面加上一个单引号:

$string = "'" . implode("','", $test) . "'";
// 'ONE', 'TWO', 'THREE', 'FOUR'

【讨论】:

  • @George 感谢您的指出。
【解决方案2】:

这个问题之前已经回答过: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)";

【讨论】:

    【解决方案3】:

    内爆数组:

    $str = "'" . implode("', '", $test) . "'";
    

    然后你可以将它添加到你的 SQL 中:

    $sql .= "(table.col IN ($str) OR table.col IS NULL)";
    

    【讨论】:

    • 你错过了引号
    • @danmullen 这将导致ONE, TWO, THREE, FOUR(缺少引号)
    • 谢谢,我知道我必须使用 implode,但就是想不通如何得到引号
    【解决方案4】:

    使用implode()。试试这个..

    $in = "'".implode("','", $test)."'";
    $sql .= "(table.col IN (".$in.") OR table.col IS NULL)";
    

    【讨论】:

      【解决方案5】:

      另一种方法是 foreach 和 rtrim: foreach($test as $v) { $str .= "'$v',"; } $str = rtrim($str, ',');

      【讨论】:

        【解决方案6】:

        您可以使用“内爆”功能来做到这一点。

        试试这个:

        $test = $go->get_stuff();
        $test = array(
            'ONE',
            'TWO',
            'THREE',
            'FOUR'
        )
        
        // expected outcome
        $sql .= "(table.col IN ('".implode("','", $test)."') OR table.col IS NULL)";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-06-08
          • 2012-08-07
          • 1970-01-01
          • 2018-07-04
          • 2014-07-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多