【问题标题】:How to do this PHP loop in a table如何在表格中执行此 PHP 循环
【发布时间】:2018-03-12 02:38:30
【问题描述】:

我使用 simple-php-dom 从其他网站获取一些 html。 然后我使用 foreach 查找 3 件事:公司名称、地址和电话。 最后,我想使用 php 循环在我的表中打印这 3 个信息。

问题:如何在表格内写循环?

这是我从其他网站获取 3 信息的 PHP 代码:

<?php  
//Get Biz Name
foreach($html->find('a[class=biz-name js-analytics-click]') as $biz_name_root){
  foreach ($biz_name_root->find('span') as $biz_name) {
    echo $biz_name->plaintext . "<br>";
  }
}

//Get Address
foreach($html->find('address') as $address){
  echo $address . '<br>';
}

// Get Phone
foreach($html->find('span[class=biz-phone]') as $phone){
  echo $phone . '<br>';
}
?>

这是我要将这 3 个信息存储到的表: 我想将$biz_name-&gt;plaintext 存储到&lt;td&gt;biz_name&lt;/td&gt;,将$address 存储到 &lt;td&gt;address&lt;/td&gt;$phone&lt;td&gt;phone&lt;/td&gt;field。

<table class="table">
  <thead class="thead-dark">
    <tr>
      <th scope="col">No</th>
      <th scope="col">Biz Name</th>
      <th scope="col">Address</th>
      <th scope="col">Phone</th>
    </tr>
  </thead>
  <tbody>
  <?php 
  for ($i=1; $i < count($html->find('address'))+2  ; $i++) { ?>
    <tr>
      <th scope="row"><?php echo $i ?></th>
      <td>biz_name</td>
      <td>address</td>
      <td>phone</td>
    </tr>
    <?php }
    ?>
  </tbody>
</table>

【问题讨论】:

    标签: php html dom


    【解决方案1】:

    您应该将所有找到的信息存储在数组中以遍历它们:

    <?php  
    //Get Biz Name
    $bisNames = array();
    foreach($html->find('a[class=biz-name js-analytics-click]') as $biz_name_root){
      foreach ($biz_name_root->find('span') as $biz_name) {
        $bizNames[] = $biz_name->plaintext;
      }
    }
    
    //Get Address
    $adresses = array();
    foreach($html->find('address') as $address){
      $adresses[] = $address;
    }
    
    // Get Phone
    $phones = array();
    foreach($html->find('span[class=biz-phone]') as $phone){
      $phones[] = $phone;
    }
    ?>
    

    然后:

    <table class="table">
      <thead class="thead-dark">
        <tr>
          <th scope="col">No</th>
          <th scope="col">Biz Name</th>
          <th scope="col">Address</th>
          <th scope="col">Phone</th>
        </tr>
      </thead>
      <tbody>
      <?php 
      for ($i=1; $i < count($html->find('address'))+2  ; $i++) { ?>
        <tr>
          <th scope="row"><?php echo $i ?></th>
          <td><?php echo $bizNames[$i]; ?></td>
          <td><?php echo $adresses[$i]; ?></td>
          <td><?php echo $phones[$i]; ?></td>
        </tr>
        <?php }
        ?>
      </tbody>
    </table>
    

    【讨论】:

    • 当我存储到数组$addresses[] = $address; 然后执行print_r($addresses) 时,数组的所有索引都为0。 Array ( [0] =&gt;address1, [0] =&gt;address2, [0] =&gt;address3 .... 所以当我在桌子上循环使用 for 时它不起作用。有什么建议吗?
    • $phones$bizNames 的值是多少?它们是您预期的还是零?尝试制作var_dump($html-&gt;find('address')) 以查看返回的内容。
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多