在循环时它只显示1个值,这是最后一个

时间:2019-02-16 10:22:26

标签: php arrays web-scraping

我试图将数组打印为表格,但实际上它并没有真正在数组中循环,它只向我显示最后一个值

</published>

我希望看到所有11个值,但是我只看到一个,它是最后一个 当我做var_dump时,它显示的很好,并且可以正确打印所有数组

**问题是我忘记了$ output。 =并且还要在开始时创建一个空的$ output =''谢谢您的帮助! 现在工作正常! **

3 个答案:

答案 0 :(得分:2)

您需要连接您的$output变量,否则它将仅显示最后一个变量,因为该变量在每次循环迭代时都会重新分配。

只需将$output =更改为$output .=

编辑:您应在循环之前用空字符串实例化该变量,因为您无法将其串联为一个未声明的变量,这将引发错误。在循环开始前添加$output ='';

答案 1 :(得分:0)

您的echo $output;仅具有一个(最后一个)值时位于最后。

它应该已经在使用foreach循环遍历所有$ currencies值的循环内。

foreach ($currencies as $currency => list($sell, $buy)) {
  $output = ' <td data-th="currency">'.$currency.'</td> <td data- 
  th="sellprice">'.$sell.'</td> <td data-th="buyprice">'.$buy.'</td> '; 
  echo $output;
}

答案 2 :(得分:0)

<?php 

//  When you are looping in foreach, you are assigning a value to `$output` everytime the loop runs and not realy appending to it. So it's showing the last one from foeach loop : 

foreach ($currencies as $currency => list($sell, $buy)) {

    $output = ' <td data-th="currency">'.$currency.'</td> <td data-th="sellprice">'.$sell.'</td> <td data-th="buyprice">'.$buy.'</td> ';
}

// You can do following : 

$output = '';

foreach ($currencies as $currency => list($sell, $buy)) {

    $output .= ' <td data-th="currency">'.$currency.'</td> <td data-th="sellprice">'.$sell.'</td> <td data-th="buyprice">'.$buy.'</td> ';
}