PHP Foreach Loop and DOMNodeList

前端 未结 2 379
一生所求
一生所求 2021-01-13 17:15

I am trying to determine the end of a foreach loop that is seeded with a collection of DOMNodeList. Currently, I am using a for loop would like to avoid having a \'magic\'

相关标签:
2条回答
  • 2021-01-13 17:56

    You can use:

    $cols->length
    

    To retrieve the number of items in a DOMNodeList.

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

    Edit: If you change you're code to this, you don't have to worry about the trailing comma, or the length:

    $output = array();
    foreach ($cols as $item) {
       $output = iconv("UTF-8", "ASCII//IGNORE", $item->nodeValue);
       $output2 = trim($output);
    
       $output[] = '"' . $output2 . '"';
    }
    $outputstring = implode(',', $output);
    
    0 讨论(0)
  • 2021-01-13 18:10
    $cols->length
    

    Should give you the number of items in the list

    for ($i = 0; $i < $cols->length; $i++) {
    
    // ...
    
    if ($i == $cols->length - 1) {
    // last column
    
    0 讨论(0)
提交回复
热议问题