我正在尝试是否可以将for循环转换为foreach循环。原因:因为我想让这段代码更通用,远离魔术数字。虽然我知道dataset中的列数,但我更倾向于使代码更通用。我尝试使用end()和next()函数来检测DOMNodeList中的最后一个元素,但没有成功。
我的最终输出将是带有如下附件的CSV格式,
“值1",”值2",“值3",”值4",“值5",”值6",“值7",”值8“
这是我的原始for循环:
$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 . "\"" . ",";
}
}发布于 2010-01-07 11:52:55
下面是一个使用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); https://stackoverflow.com/questions/2018059
复制相似问题