PHP - 将foreach循环重写为for循环以获得计数器

时间:2014-08-06 12:09:30

标签: php loops foreach

我尝试将两个foreach循环重写为for循环,以便我能够将它们停在3.这是第一个简单的循环原始:< / p>

<?php foreach ($marketing[0]['values'] as $company) { ?>
            <tr>
              <td><?php echo $company['label']; ?></td>
              <td><?php echo $company['value']; ?></td>
            </tr>
          <?php } ?>

这是我尝试重写:

 <?php 
        for($i = 0; $i < 4; ++$i) { 
        $company = $marketing[0][$i]['values']; 
      ?>
        <tr>
          <td><?php echo $company['label']; ?></td>
          <td><?php echo $company['value']; ?></td>
        </tr>            
      <?php } ?>

这是我尚未尝试的第二个稍微复杂的foreach循环。

<?php foreach ($sales as $sale) { ?>
          <tr>
            <td><?php echo $sale['key']; ?></td>
            <td>
              <?php 
                foreach ($sale['values'] as $values) {
                  if ($values['x'] == $currentTeam) {
                    echo $values['y'];
                  }
                }                 
              ?>
            </td>
          </tr>
          <?php } ?>

2 个答案:

答案 0 :(得分:2)

你总是可以使用休息。 http://php.net/manual/en/control-structures.break.php

<?php $counter = 0; ?>
<?php foreach ($marketing[0]['values'] as $company) { ?>
    <?php if ($counter == $maxLimit) break; ?>
    <tr>
        <td><?php echo $company['label']; ?></td>
        <td><?php echo $company['value']; ?></td>
    </tr>
    <?php $counter++; ?>
<?php } ?>

答案 1 :(得分:1)

你差不多已经

<?php 
  $maxLimit = 3; //you could get maxlimit from elsewhere rather than hardcoding it

  //use count() to get the length of an array in PHP
  for($i = 0; $i < count($marketing[0]); ++$i) 
  { 
    $company = $marketing[0][$i]['values']; 
    if($i > $maxLimit) break;
  ?>
    <tr>
      <td><?php echo $company['label']; ?></td>
      <td><?php echo $company['value']; ?></td>
    </tr>            
  <?php } ?>

作为替代方案,您可以在旁边引入一个计数器字段

      <?php 
          $salesCounter = 0;
          $maxSalesCounter = 3;
          foreach ($sales as $sale) 
          { 
      ?>
      <tr>
        <td><?php echo $sale['key']; ?></td>
        <td>
          <?php 
            foreach ($sale['values'] as $values) 
            {
              if($salesCounter > maxSalesCounter) break;
              if ($values['x'] == $currentTeam) 
              {
                echo $values['y'];
                $salesCounter++;
              }

            }                 
          ?>
        </td>
      </tr>
      <?php } ?>