编写并保存在变量中时字符串不同

时间:2016-11-02 09:34:55

标签: php

好的,所以我对字符串有这个令人困惑的问题。我正在使用循环来构造字符串,并使用print_r($exclude)来查看结果。字符串的输出是:

101102135

......这是正确的。然后我试图在一个WordPress查询的参数数组中使用$exclude

'terms' => array($exclude),

简而言之,这应该排除上述ID类别的帖子。但这不符合预期。 除非如果我直接写这样的数字,它就有效:

'terms' => array(101,102,135),

那么$exclude - 字符串和手动编写数字之间有什么区别......!?

3 个答案:

答案 0 :(得分:2)

您需要使用php的爆炸功能。

尝试以下代码:

'terms' => explode(',', $exclude)

有关详细信息,请参阅此链接 - http://www.w3schools.com/php/func_string_explode.asp

答案 1 :(得分:2)

当你这样做时

'terms' => array($exclude)

您的terms数组如下所示:

Array
(
    [0] => 101,102,135
)

<强>解决方案

'terms' => explode(',', $exclude)

$exclude变为

Array
(
    [0] => 101
    [1] => 102
    [2] => 135
)

您正在为数组中的第0个键指定一个字符串,而您应该传递数组元素。

explode会根据传递的delimiter(在您的情况下为逗号)将字符串拆分为数组。

答案 2 :(得分:1)

如果您print_r array($exclude) 它会给出

Array
(
    [0] => 101,102,135
)

你需要的是

Array
(
    [0] => 101,
    [1] => 102,
    [2] => 135
)

即,将这些数字作为数组元素的数组 所以只需'terms' => explode(',', $exclude),你就会好起来...... http://php.net/manual/en/function.explode.php