我的输出工作完美,只有一个例外:有些人没有电话号码,如果没有可用的电话号码,我不想包括标题(电话)。我已经为输出解决了这个问题。我试着在Phone周围包装一个foreach,但当然这重复了foreach person记录组。
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th> <!-- This <th> should not display if all phone numbers are empty. -->
</tr>
<?php foreach ($persons as $person) : ?>
<tr>
<td><?php $person['name']; ?></td>
<td><?php $person['email']; ?></td>
<?php if($person['phone'] != '') { ?> // removes column box if there is no phone number.
<td><?php $person['phone']; ?></td>
<?php } ?>
<?php
$countEle = count($persons);
$count = 0;
foreach($persons as $person) {
if(empty($person['phone'])) {
$count++;
}
}
//then you could check as
?>
<?php if($count < $countEle) { ?>
<th>Phone</th>
<?php } ?>
提前遍历数组,检查是否有任何人有电话号码,然后在条件中使用它。下面是PHP 5.3+的一行代码:
<?php $hasPhone = array_reduce($persons, function ($hasPhone, $person) { return $hasPhone || $person['phone']; }, false); ?>
<table>
<tr>
...
<?php if ($hasPhone) : ?>
<th>Phone</th>
<?php endif; ?>
</tr>
<?php foreach ($persons as $person) : ?>
..
<?php if ($person['phone']) : ?>
<td><?php $person['phone']; ?></td>
<?php endif; ?>
<?php endforeach; ?>