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

I'm trying to rewrite two foreach loops as for loops so that I am able to stop them at 3. Here is the first and simple loop's original:

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

Here is my attempted re-write:

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

Here is the second and slightly more complicated foreach loop that I haven't attempted yet.

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

You can always use break. 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 } ?>

You were almost there already

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

As an alternative, you could introduce a counter field on the side

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