【问题标题】:concatinating two array elements with a string within a foreach loop在 foreach 循环中将两个数组元素与字符串连接起来
【发布时间】:2019-06-12 11:34:27
【问题描述】:

我正在尝试将两个数组元素与字符串“OR”组合并创建一个元素字符串。

数组如下所示: $myarray = array(2282396,1801345)

这是我使用的代码。

$bool = ' OR ';
foreach($myarray as $element){

echo $element .= $bool;
}

我试图在使用 foreach 循环进行循环后获取此输出。 2282396 OR 1801345

但是,我得到的输出如下所示: 2282396 OR 1801345 OR

如何去掉第二个元素后的“OR”?提前致谢

【问题讨论】:

    标签: php arrays concat


    【解决方案1】:

    您必须检查您是否处于第一次/最后一次迭代中。

    $first = true;
    $bool = ' OR ';
    foreach ($myarray as $element) {
        if (!$first) {
            echo $bool;
        }
        echo $element; 
        $first = false;
    }
    

    如果您的数组由数字索引 0-x 索引,则您可以使用

    $bool = ' OR ';
    foreach ($myarray as $key => $element) {
        if ($key > 0) {
            echo $bool;
        }
        echo $element; 
    }
    

    【讨论】:

    • @dWinder:当然,我知道。 OP 要求 foreach 循环。它可以是有问题的简化代码,可能不需要只使用echo等。OP要求foreach循环,所以有foreach循环的答案。
    • 像@panther 的魅力一样工作。我接受这个作为答案
    • 我认为 OP 不知道他想要什么 - 这是我们的工作,不仅要回答他,还要教他 - 因为有时他不知道自己需要什么
    【解决方案2】:

    implode 用作:

    echo implode(" OR ", $myarray);
    

    文档implode

    现场示例:3v4l

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多