【问题标题】:PHP Foreach Loop and DOMNodeListPHP Foreach 循环和 DOMNodeList
【发布时间】:2010-01-06 22:15:55
【问题描述】:

我正在尝试确定以 DOMNodeList 集合为种子的 foreach 循环的结束。目前,我正在使用 for 循环,希望避免在那里出现“魔术”数字。我知道只有 8 列,但我希望我的代码通用用于其他应用程序。

是否可以将其转换为 Foreach 循环?我已经尝试过 end() 和 next() 函数,但它们没有返回任何数据,我怀疑它们只适用于数组而不是这个 DOMNodeList 集合。

代码正在构建一个没有尾随','的 CSV 文件

当前输出为:

"值 1","值 2","值 3","值 4","值 5","值 6","值 7","值 8"

下面是代码示例:

$cols = $row->getElementsByTagName("td");
$printData = true;

// Throw away the header row
if ($isFirst && $printData) {
   $isFirst = false;
   continue;
}

for ($i = 0; $i <= 8; $i++) {
   $output = iconv("UTF-8", "ASCII//IGNORE", $cols->item($i)->nodeValue);
   $output2 = trim($output);
   if ($i == 8) {
      // Last Column
      echo "\"" . $output2 . "\"" . "\n";
   } else {
      echo "\"" . $output2 . "\"" . ",";
   }
}

【问题讨论】:

    标签: php foreach


    【解决方案1】:

    你可以使用:

    $cols->length
    

    检索 DOMNodeList 中的项目数。

    http://php.net/manual/en/class.domnodelist.php

    编辑: 如果您将代码更改为此,您不必担心结尾的逗号或长度:

    $output = array();
    foreach ($cols as $item) {
       $output = iconv("UTF-8", "ASCII//IGNORE", $item->nodeValue);
       $output2 = trim($output);
    
       $output[] = '"' . $output2 . '"';
    }
    $outputstring = implode(',', $output);
    

    【讨论】:

      【解决方案2】:
      $cols->length
      

      应该给你列表中的项目数

      for ($i = 0; $i < $cols->length; $i++) {
      
      // ...
      
      if ($i == $cols->length - 1) {
      // last column
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-14
        • 2016-09-26
        • 2012-07-19
        • 2010-12-17
        • 2015-12-10
        • 1970-01-01
        相关资源
        最近更新 更多