在另一个值之上回显值

时间:2017-11-23 12:16:29

标签: php

我认为这很简单但我似乎没有完成它。我想要做的是显示我从FOREACH循环获得的值,而不是其他回显值。

function writeMsg($total) {
echo $total. "< This must display First";
}

foreach ($array as $value) {
   echo $value["Price"]."<br>";
   $total = $value["Total"];
}

writeMsg($total);

请注意,我已经回显了foreach中的值,但我想要的是回应我从

获取的变量
$total = $value["Total"];

 echo $value["Price"]."<br>";

我希望你们理解我的问题!

3 个答案:

答案 0 :(得分:2)

您可以使用output buffering

ob_start(); // everything echo'ed now is buffered
foreach ($array as $value){
    echo $value["Price"]."<br>";
    $total = $value["Total"];
}
$all_the_echoes = ob_get_clean(); // capture buffer to variable

writeMsg($total); // echoes the total
echo $all_the_echoes; // echoes the captured buffer

请注意,可能有一个更清晰的解决方案,但除非您更新问题,否则我猜测您要实现的目标。

答案 1 :(得分:0)

我不完全确定要获得什么,但我的猜测是:

function writeMsg($total) {
echo $total. "< This must display First";
}
$total = 0;
$prices = array();

foreach ($array as $value){
    $prices [] = $value["Price"];
    $total += $value["Total"];
}

echo implode("<br>", $prices);
echo "<br>";
writeMsg($total);

答案 2 :(得分:0)

我认为你想要的东西看起来像这样。在foreach循环中,您希望累积数据并在以后回显它们。在那里你可以选择首先回应什么。

function writeMsg($total) {
    echo $total. "< This must display First";
}


$total = 0;
$prices = '';

foreach ($array as $value){
    // concatenate all prices into a single string. echo this later (after echo of totals)
    $prices .= $value["Price"]."<br>";

    // sum up total of all values
    $total += $value["Total"];
}

writeMsg($total);
echo $prices;