【问题标题】:PHP foreach nested tablePHP foreach 嵌套表
【发布时间】:2017-09-10 05:49:51
【问题描述】:
<table style="width: 600px" class="slicedTable">
     <tr>
      <th>Spetsialist</th>
      <th>Tunnid</th>
     </tr>


<tr>            
       <?php foreach($specs as $specName => $spec): ?>
        <td><?php echo $specName?>
        <tr>
       <?php endforeach; ?>


<td>
        <?php foreach($tunnid as $tund): ?>
           <td><?php echo $tund?></td>

       </td>
       <?php endforeach; ?>
     </tr>
 </table>

我需要这个来打印出一个普通的表格,如下所示:
名称 1 - 值 1
name2 - value2

规格:

$specs = array();

            foreach($data as $row) {
                $workerName = $row['Worker']['name'];
                if (!isset($specs[$workerName])) {
                    $specs[$workerName] = array('procs' => array(), 'extras' => array());
                }

但是我似乎无法做到这一点,请帮助。

【问题讨论】:

  • $spec 是“名称”,$tund 是“值”吗?
  • 为什么要关桌3次?
  • 是的,完全一样
  • 不小心把它丢了,我绝望地试了两张相邻的桌子。
  • 你的阵列是什么样子的?

标签: php foreach html-table nested


【解决方案1】:

这是我为你修复的代码:

假设$spec 中的元素数量等于或大于$tunnid 中的元素数量。在 coder 的角度,count($spec) &gt;= count($tunnid).

<table style="width: 600px" class="slicedTable">
   <tr>
      <th>Spetsialist</th>
      <th>Tunnid</th>
   </tr>
   <?php 
      $i = 0;
      foreach($specs as $specName => $spec): 
    ?>
   <tr>            
       <td><?php echo $specName; ?></td>
       <td><?php echo isset($tunnid[$i]) ? $tunnid[$i] : '-'; ?></td>
    </tr>
    <?php 
         $i++;
      endforeach; 
    ?>
 </table>

我承认,这并不是一个优雅的解决方案。

【讨论】:

  • 但如果不是呢?现在表格看起来不错,但只有当数字相同时,正确的值才会彼此相邻。
  • 如果$tunnid中的元素个数大于$specs中的元素个数,则$tunnid中剩余的元素将不显示。
  • 好的,那么我的查询一定有问题,我没有得到正确名称旁边的正确值..
  • 我更新了答案,现在包括 if count($spec) &gt;= count($tunnid)
【解决方案2】:

更新
看起来你的数组可能有不同的长度,所以我更新了下面的代码来处理这种情况(哪个数组更长并不重要)。


你可以这样做:

<table style="width: 600px" class="slicedTable">
    <tr>
        <th>Spetsialist</th>
        <th>Tunnid</th>
    </tr>
<?php $len1 = count($specs); $len2 = count($tunnid);
      $specsKeys = array_keys($specs);
      for ($i = 0; $i < max($len1, $len2); $i++) {
          $name  = ($i < $len1) ? $specsKeys[$i] : ""; 
          $value = ($i < $len2) ? $tunnid[$i] : ""; ?>
    <tr>
        <td><?php echo($name); ?></td>
        <td><?php echo($value); ?></td>
    </tr>
<?php } ?>
</table>

另请参阅此short demo(*更新*)。

【讨论】:

  • 如果你看一下提供的演示,你可以看到没有错误。我能想到在您的代码中引发错误的唯一原因是$specs$tunnid 的长度不同,或者您在代码的其他地方使用了名为$i 的变量。无论如何,如果没有确切的错误(和代码),我无法弄清楚您的代码中的问题是什么。
  • @user2485439:考虑到您在另一个答案中的 cmets,您的数组似乎可能有不同的长度。我知道您现在可能已经解决了您的问题,但无论如何我更新了我的答案以能够处理不同长度的数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 2012-09-17
相关资源
最近更新 更多