如果不存在变量,请使用 PHP 中的前一个变量


Use previous variable from PHP foreach if none exists

我目前正在做一个小项目,该项目将工作轮换从简单的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

有人能帮忙吗?谢谢!

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

仅当当前行不为空时,这才会为 $shift 分配一个新值。

或者:

$shift = (empty($row->children(0)->plaintext ? $shift : $row->children(0)->plaintext);
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 />";
    }
}