2014-09-06 117 views
-1

此代碼獲取表。刪除第一個或特定的子節點xpath

我想刪除表中的第一個和第二個tr標籤。

$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), 
    ); 
} 
} 

和問題2

在以下表格TR有兩個類--- EvenRow_Print和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), 
    ); 
    } 
} 

我怎樣才能迴響在一個2D陣列既TR。 例如。

 Array(

     [0] => Array(
    //array 
       ) 

} 

感謝的

+0

請問每個問題只有一個問題。一次提出兩個問題在Stackoverflow上不起作用。 – hakre 2014-10-12 21:35:04

回答

1

問題1 - 有不同的方式來跳過第一個和最後一個元素,例如使用array_shift()刪除第一個條目,使用array_pop()刪除最後一個條目。但是現在還不清楚是否更好地保留陣列,因此可以像使用計數器那樣以簡單的方式跳過foreach中的兩個條目,繼續第一個條目並打破最後一個條目:

$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 
    } 
+0

在foreach中我有一個if。我不知道如何設置如果($ i == 0)在foreach中。 – 2014-09-06 13:11:09

+0

如果你已經擁有了不應該的事;只要放在「if」之上即可;如果是第一個或最後一個條目,則該foreach將跳過或打破;如果不是的話,它會繼續到你的下一步,如果應該在我的答案部分添加佔位符「... //處理所有其他條目」 – 2014-09-06 13:27:37