2013-10-22 61 views
0

我目前正在一個小型項目,將工作rota從簡單的HTML表格轉換爲YAML輸出。如果額外的員工工作在同一個工作表上,我所抓取的表格不會重複日期,而更願意只顯示一次。這意味着,當我的PHP腳本在表中工作時,對於某個日期的額外工作人員,則不設置日期,導致一個空值。到目前爲止,我有以下幾點:使用以前的變量從PHP foreach,如果不存在

<?php 

include('simple_html_dom.php'); 

$html = str_get_html('<table> 
         <tbody> 
         <tr> 
         <td>Day</td> 
         <td>Jack</td> 
         </tr> 
         <tr> 
         <td></td> 
         <td>Jill</td> 
         </tr> 
         <tr> 
         <td>Night</td> 
         <td>John</td> 
         </tr>   
         </tbody> 
         </table>'); 



foreach($html->find('table') as $element) { 

    $td = array(); 
    foreach($element->find('tr') as $row) { 

    $shift = $row->children(0)->plaintext; 
    $staff = $row->children(1)->plaintext; 
     echo $shift; 
     echo "<br />"; 
     echo "Staff: " . $staff; 
     echo "<br />"; 
     echo "<br />"; 

    } 

} 

exit; 
?> 

此輸出如下:

Day 
Staff: Jack 


Staff: Jill 

Night 
Staff: John 

我不知道怎麼做的,是讓PHP使用相同的變量設置從以前的foreach循環,如果不存在。這樣,我可以輸出如下:

Day 
Staff: Jack 

Day 
Staff: Jill 

Night 
Staff: John 

任何人都可以協助嗎?謝謝!

+4

只是檢查如果變量是空的,如果是這樣,不要再進行分配。這樣它將使用前面迭代的值 – billyonecan

回答

2
if(!empty($row->children(0)->plaintext)){ 
    $shift = $row->children(0)->plaintext; 
} 
... 

如果當前行不爲空,這將只是一個新的值賦給$shift

或者:

$shift = (empty($row->children(0)->plaintext ? $shift : $row->children(0)->plaintext); 
+0

完美!非常感謝:)不能相信它是如此輕微! – jordanmerrick

1
foreach ($html->find('table') as $element) { 
    $lastShift = $lastStaff = ''; 
    $td = array(); 
    foreach ($element->find('tr') as $row) { 

     $shift = $row->children(0)->plaintext; 
     $staff = $row->children(1)->plaintext; 
     if (empty($staff)) { 
      $staff = $lastStaff; 
     } 
     if (empty($shift)) { 
      $shift = $lastShift; 
     } 
     echo $shift; 
     echo "<br />"; 
     echo "Staff: " . $staff; 
     echo "<br />"; 
     echo "<br />"; 
     $lastStaff = $staff; 
     $lastShift = $shift; 
    } 
} 

OR

foreach ($html->find('table') as $element) { 
    $shift = $staff = ''; 
    $td = array(); 
    foreach ($element->find('tr') as $row) { 
     if (!empty($row->children(0)->plaintext)) { 
      $shift = $row->children(0)->plaintext; 
     } 
     if (!empty($row->children(1)->plaintext)) { 
      $staff = $row->children(1)->plaintext; 
     } 
     echo $shift; 
     echo "<br />"; 
     echo "Staff: " . $staff; 
     echo "<br />"; 
     echo "<br />"; 
    } 
} 
+0

謝謝!精湛的工作。我不得不將標記爲零的答案正確,因爲它首先通過了,但是測試了它,它也完全按照要求工作。 – jordanmerrick