Php解析的html表和计数特定<;td>;相似
这个问题紧接着另一个刚刚解决的问题Php解析的html表和计数特定<;td>;相似,php,html-table,html-parsing,Php,Html Table,Html Parsing,这个问题紧接着另一个刚刚解决的问题 现在我想做一个不同的计数,更难计算。 在我解析的HTML表中,每一行都包含两个非常相似的相应的“td”(第4和第5行): (1) 根据前面问题中的代码,您应该已经有了以下内容: $targetString = 'TARGET STRING'; $rows = $table->find('.trClass'); $count = 0; foreach($rows as $row) { foreach($row->find('td') as
现在我想做一个不同的计数,更难计算。
在我解析的HTML表中,每一行都包含两个非常相似的相应的“td”(第4和第5行):
(1) 根据前面问题中的代码,您应该已经有了以下内容:
$targetString = 'TARGET STRING';
$rows = $table->find('.trClass');
$count = 0;
foreach($rows as $row) {
foreach($row->find('td') as $td) {
if ($td->innertext === $targetString) {
$count++;
break;
}
}
}
由于您已经在查看td,所以执行您所说的操作将非常简单——“从左数“td”位置,并仅选择第5个位置”。只要你知道这绝对是你可以做的第五个td:
foreach($rows as $row) {
$tdcount = 0;
foreach($row->find('td') as $td) {
//...
//Bear in mind the first td will have tdcount=0, second tdcount=1 etc. so fifth:
if($tdcount === 4 && ( 'Yes'===$td->innertext || 'No'===$td->innertext) ) {
//do whatever you want with this td
}
$tdcount++;
}
}
您确实需要更新某些部分。首先,您需要第4和第5个元素,因此您必须检查它(保留计数器或使用for循环)。其次,在这种情况下不需要中断,因为它会停止循环
代码:
foreach($rows as $row) {
$tdcount = 0;
foreach($row->find('td') as $td) {
//...
//Bear in mind the first td will have tdcount=0, second tdcount=1 etc. so fifth:
if($tdcount === 4 && ( 'Yes'===$td->innertext || 'No'===$td->innertext) ) {
//do whatever you want with this td
}
$tdcount++;
}
}
<?php
$targetString = 'No';
$rows = $table->find('.trClass');
$count = 0;
foreach($rows as $row) {
$tds = $row->find('td');
for (i = 0; i < count($tds); $i++) {
// Check for the 4th and 5th element
if (($i === 3 || $i === 4) && $tds[$i]->innertext === $targetString) {
$count++;
}
}
}