问题
this code get table.
I want to remove first and second tr tag in the table.
$data = array();
$table_rows = $xpath->query('//table[@class="adminlist"]/tr');
if($table_rows->length <= 0) { // exit if not found
echo 'no table rows found';
exit;
}
foreach($table_rows as $tr) { // foreach row
$row = $tr->childNodes;
if($row->item(0)->tagName != 'tblhead') { // avoid headers
$data[] = array(
'Name' =>trim($row->item(0)->nodeValue),
'LivePrice' => trim($row->item(2)->nodeValue),
'Change'=> trim($row->item(4)->nodeValue),
'Lowest'=> trim($row->item(6)->nodeValue),
'Topest'=> trim($row->item(8)->nodeValue),
'Time'=> trim($row->item(10)->nodeValue),
);
}
}
and question 2
In the bellow table tr have two class --- EvenRow_Print and OddRow_Print ---
$data = array();
$table_rows = $xpath->query('//table/tr');
if($table_rows->length <= 0) {
echo 'no table rows found';
exit;
}
foreach($table_rows as $tr) { // foreach row
$row = $tr->childNodes;
if($row->item(0)->tagName != 'tblhead') { // avoid headers
$data[] = array(
'Name' =>trim($row->item(0)->nodeValue),
'LivePrice' => trim($row->item(2)->nodeValue),
'Change'=> trim($row->item(4)->nodeValue),
'Lowest'=> trim($row->item(6)->nodeValue),
'Topest'=> trim($row->item(8)->nodeValue),
'Time'=> trim($row->item(10)->nodeValue),
);
}
}
How can I echo both tr in one 2d array . examp.
Array(
[0] => Array(
//array
)
}
Thank's
回答1:
For question 1 - there are different ways to skip the first and last element, e.g. removing the first entry using array_shift()
and the last entry using array_pop()
. But as it's not clear if it'd be better to keep the array as it is, it's possible to skip both entries in the foreach
in an easy way like using a counter, continuing for the first entry and breaking for the last:
$i = 0;
$trlength = count($table_rows);
foreach( ...) {
if ($i == 0) // is true for the first entry
{
$i++; // increment counter
continue; // continue with next entry
}
else if ($i == $trlength - 1) // last entry, -1 because $i starts from 0
{
break; // exit foreach loop
}
.... // handle all other entries
$i++; // increment counter in foreach loop
}
来源:https://stackoverflow.com/questions/25696986/remove-first-or-specific-child-node-xpath