PHP - 合并多个 while 循环的输出

标签 php while-loop return concatenation wordpress-shortcode

我需要返回一个结果,该结果组合了通过多个 WHILE 循环从多个数组创建的语句。

我有四个数组,并试图根据条件获得不同的输出。这些数组的结构都是相同的键,并且这些键对应于一个事件。其中一个数组的每个键可能有多个值,如果该数组包含多个值,则需要检查该特定数组内的值的数量,以便使用不同的输出结构。

foreach ($closures as $closure) {

//stuff

    for ( $i = 0; $i < $count; $i++){        
        $vcount = count( $locations[$i] );

        while ( $vcount < 2 ) {
            $result = "The ".$venue[$i]." has been reserved for an <a href=".$eventURLs[$i].">event</a> today from ".$startTime[$i]." - ".$endTime[$i].".<br>";
            //print_r($result); //looks good printed...  
            break;
        }

        while ($vcount > 1 ) {
            $result =  "The ".$venue[$i]."s have been reserved for an <a href=".$eventURLs[$i].">event</a> today from ".$startTime[$i]." - ".$endTime[$i].".<br>";
            //print_r($result); //looks good printed... 
            break;
        }
    }
    return $result;
    break;
}

我已经尝试了“break”的每种组合,当然它给了我不同的输出,但没有一个是正确的。 我尝试为每个 while 循环分配不同的变量($result1 和 $result2)。 我尝试在循环内部和外部用 $result[$i] 替换 $result 。 我尝试过移动“return...”的位置。

虽然使用 print_r 如图所示,它显示完美,但我不知道如何将这些结果放入单个输出中。

我只能通过我的短代码输出第一个结果,并且在尝试将它们组合成这样的语句时只能设法获得两个结果(每个循环一个):

$message = "".result1."".result2."";

最佳答案

您可以使用 .= 赋值运算符将结果值相互连接

foreach ($closures as $closure) {

//stuff

for ( $i = 0; $i < $count; $i++){        
    $vcount = count( $locations[$i] );
    // initiate the result
    $result = "";
    while ( $vcount < 2 ) {
        // concatinate the value to $result
        $result .= "The ".$venue[$i]." has been reserved for an <a href=".$eventURLs[$i].">event</a> today from ".$startTime[$i]." - ".$endTime[$i].".<br>";
        //print_r($result); //looks good printed...  
        break;
    }

    while ($vcount > 1 ) {
        // concatinate the value to $result again
        $result .=  "The ".$venue[$i]."s have been reserved for an <a href=".$eventURLs[$i].">event</a> today from ".$startTime[$i]." - ".$endTime[$i].".<br>";
        //print_r($result); //looks good printed... 
        break;
    }
}
return $result;
break;
}

关于PHP - 合并多个 while 循环的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624414/

相关文章:

php - 如何使用数据库中的值创建 PHP 两列表?

python - 使用 PYTHON 计算在 while 循环中设置新变量

php - 多个 while 循环无法正常工作

python - 从函数返回多个值的最佳方法?

php - 使用 Zend_Validate_Date 对时间字符串进行验证

php - 如何使用循环插入多个值?

php:拆分字符串直到第一次出现数字

Javascript 循环 & setInterval

python - 从 python 脚本返回值的最佳方法

c++ - 在 C++ 中使用 return 语句退出函数