【问题标题】:while looping it prints me only 1 value and it's the last one [closed]而循环它只打印我1个值,它是最后一个[关闭]
【发布时间】:2019-02-16 10:22:26
【问题描述】:

我正在尝试将我的数组打印为表格,但实际上它并没有真正在数组内循环,它只打印最后一个值

<?php
$url='http://myurl.com/';
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$html = curl_exec($curl);
;
$pro=array();
preg_match_all("/<td>[0-9]{1,3}(\.[0-9]{3})*.[0-9]+DA<\/td>",$html,$match);
$pro['prix']=$match['0'];

preg_match_all('!<td><a href=".*">\K(.+?(?=<\/a><\/td>))!',$html,$match);
$pro['nom']=$match['0'];
$currencies = array_combine($pro['nom'], array_chunk($pro['prix'], 2));

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> '; 
}
curl_close($curl);
?>
<table class="rwd-table">
    <tr>
        <th>Devises</th>
        <th>Achat</th>
        <th>Vente</th>
    </tr>
<?php echo $output ?>
</table>

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

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

【问题讨论】:

  • $output = 使$output .= 然后它将连接到该变量而不是覆盖它
  • 痛苦的世界等待尝试使用正则表达式解析 HTML...考虑改用 DOMDocument / DOMXPath

标签: php arrays web-scraping


【解决方案1】:

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

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

编辑:你应该在循环之前用一个空字符串来实例化变量,因为你不能连接到一个未声明的变量,它会抛出一个错误。在循环开始前添加$output ='';

【讨论】:

  • 对于 TYPO,我们通常只需发表评论,然后投票结束问题。错字对其他人几乎没有任何用处,毕竟这是 SO 的重点,成为开发人员可搜索的有用资源
【解决方案2】:
<?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> ';
}

【讨论】:

  • 对于 TYPO,我们通常只需发表评论,然后投票结束问题。拼写错误对其他人几乎没有任何用处,毕竟这是 SO 的重点,成为开发人员可搜索的有用资源
  • @RiggsFolly 我非常不同意并认为解释这个错字如何影响错误同样重要。仅仅强调错字并不能帮助提问的人知道为什么会发生这个错误。
  • 它是一个字符串错字,然后评论才有意义,这个错字完全改变了逻辑。评论不够
  • 我认为我的评论实际上很好地涵盖了这个问题
【解决方案3】:

当您的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;
}

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多