0

我目前正在开发一个小型项目,该项目会将工作列表从简单的 HTML 表转换为 YAML 输出。如果其他工作人员在同一个工作人员工作,我正在抓取的表格不会重复日期,宁愿只显示一次。这意味着当我的 PHP 脚本在表格中运行时,对于特定日期的其他员工,则没有设置日期,从而导致空值。到目前为止,我有以下内容:

<?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

2 回答 2

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

$shift如果当前行不为空,这只会分配一个新值。

或者:

$shift = (empty($row->children(0)->plaintext ? $shift : $row->children(0)->plaintext);
于 2013-10-22T08:14:21.833 回答
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;
    }
}

或者

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 />";
    }
}
于 2013-10-22T08:16:07.283 回答