当前位置: 动力学知识库 > 问答 > 编程问答 >

php foreach nested table

问题描述:

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

I need this to print out a regular table where it goes like:


name 1 - value1


name2 - value2

Specs:

$specs = array();

foreach($data as $row) {

$workerName = $row['Worker']['name'];

if (!isset($specs[$workerName])) {

$specs[$workerName] = array('procs' => array(), 'extras' => array());

}

However I can't seem to accomplish this, help please.

Thanks!

网友答案:

UPDATE:
Seems like your arrays might have different lengths, so I updated the code below to handle such a situation (it doesn't matter which array is longer).


You could do it like this:

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

See, also, this short demo (*updated*).

网友答案:

Here is the code I fix for you:

Assuming the number of elements in $spec is same as or more than the number of elements in $tunnid. In coder's perspective, count($spec) >= 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>

Not really an elegant solution, I admit.

分享给朋友:
您可能感兴趣的文章:
随机阅读: