【问题标题】:PHP - Combine outputs from multipe while loopsPHP - 组合来自多个 while 循环的输出
【发布时间】:2019-08-23 10:28:20
【问题描述】:

我需要返回一个结果,该结果将通过多个 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."";

【问题讨论】:

    标签: php while-loop return concatenation wordpress-shortcode


    【解决方案1】:

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

    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;
    }
    

    【讨论】:

    • 今天你让我的前额免于瘀伤,我的办公桌免于凹痕。谢谢!
    猜你喜欢
    • 2011-01-30
    • 2012-01-02
    • 2011-02-28
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多