2010-01-07 55 views
0

我想看看我是否可以將for循環轉換爲foreach循環。原因:因爲我想讓這個代碼更通用,遠離魔術數字。雖然我知道數據集中的列數,但我寧願讓代碼更通用。我嘗試過使用end()和next()函數來嘗試檢測DOMNodeList中的最後一個元素,但我沒有成功。PHP Foreach循環和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 . "\"" . ","; 
    } 
    } 

回答

2

下面是一個如何在foreach做一個例子。雖然您始終可以使用$cols->length來獲取列表中的節點數,這也可以使用for循環來解決您的問題。

// assume there is an array initialized called outside of the loop for the rows called $lines 
    $cols = $row->getElementsByTagName("td"); 

    $row = array(); 
    foreach($cols as $item) 
    { 
    $raw = $item->nodeValue; 
    $row[] = '"'.trim(iconv("UTF-8", "ASCII//IGNORE", $raw)).'"'; 

    } 
    $lines[] = implode(',', $row); // turn the array into a line 

    // this is outside the loop for rows 
    $output = implode("\n", $lines);