简体   繁体   中英

Break foreach loop 3

I have this foreach loop for an array. I want to stop it after one cycle.

foreach ($r['result']['mounts'] as $item) echo '

                <li class="span3 clearfix" data-tag=', $item['qualityId'], 
  '>
                 <div class="element-item ', $item['qualityId'], '" data-category="element-item ', $item['qualityId'], '">

                            <a
                                    href="//de.wowhead.com/item=', 
 $item['itemId'], '"
                                    class="', $item['qualityId'], '"
                            >
                                    <img
                                            src="http://wow.zamimg.com/images/wow/icons/large/', $item['icon'], '.jpg"
                                            alt="', htmlspecialchars($item['name']), '"
                                    >
                            </a>
                   </div></li>';

  break;
 echo '

The array has 500 numeric keys.

[result] => Array
    (
        [mounts] => Array
            (
                [0] => Array
                    (
                        [name] => Elfenbeinfarbener Falkenschreiter
                        [itemId] => 142369
                        [qualityId] => 4
                        [icon] => inv_ability_mount_cockatricemount_white
                    )

                [1] => Array
                    (
                        [name] => Tundramammut des Reisenden
                        [itemId] => 44234
                        [qualityId] => 4
                        [icon] => ability_mount_mammoth_brown_3seater
                    )

                etc.

The problem is that after one loop the whole array gets echo out again.

Why loop at all then? Why not just grab the first row:

$item = $r['result']['mounts'][0];

You have forgot about curly brackets:

foreach ($r['result']['mounts'] as $item) {
  echo '...';
  break;
}
foreach ($r['result']['mounts'] as $item) 
{
  echo '<li class="span3 clearfix" data-tag=', $item['qualityId'], '>
            <div class="element-item ', $item['qualityId'], '" data-category="element-item ', $item['qualityId'], '">
              <a href="//de.wowhead.com/item=', $item['itemId'], '" class="', $item['qualityId'], '">
                <img src="http://wow.zamimg.com/images/wow/icons/large/', $item['icon'], '.jpg" alt="', htmlspecialchars($item['name']), '" >
              </a>
            </div>
          </li>';

  break;
}

but why you want to loop if you want first cycle only ?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM