简体   繁体   English

在PHP foreach循环内仅执行一次操作

[英]Do something Inside a PHP foreach Loop Only Once

I am using a foreach loop to create a brands page for our Magento store. 我正在使用foreach循环为我们的Magento商店创建品牌页面。 In the loop every 5 items are put into an un-ordered list. 在循环中,每5个项目放入一个无序列表。 They are also split up by letters of the alphabet (A - D, E - H, I - L, M - P, Q - U, V - Z). 它们也按字母(A-D,E-H,I-L,M-P,Q-U,V-Z)分开。 I need to insert a header before each set of lists. 我需要在每组列表之前插入一个标题。 For example: 例如:

<h2>A - D</h2>
<ul>
    <li>Brand 1</li>
    <li>Brand 2</li>
    <li>Brand 3</li>
    <li>Brand 4</li>
    <li>Brand 5</li>
</ul>

This is how I am getting the brands and splitting them up: 这就是我获得品牌并将其拆分的方式:

<?php foreach($brands as $brand) : ?>
    <?php $name = $brand->getName(); ?>

    <?php if((substr($name, 0, 1) == 'A') || (substr($name, 0, 1) == 'B') ||
    (substr($name, 0, 1) == 'C') || (substr($name, 0, 1) == 'D')) : ?>

        <?php if($count % 5 == 0) : ?>
            </ul><ul>
        <?php endif; ?>

        <li><a href="<?php echo $brand->getUrl(); ?>">
            <?php 
                $id = $brand->getId(); 
                $imageUrl = Mage::getModel('catalog/category')->load($id)->getThumbnailUrl();
            ?>
            <img src="<?php echo $imageUrl; ?>" alt="<?php echo $name; ?>">
        </a></li>

        <?php $count++; ?>
    <?php endif; ?>
<?php endforeach; ?>

I thought I could insert the header into the right place by counting how many brands there are for each set of 4 or 5 letters then doing the same as what I have done to put in the 's. 我以为可以将标头插入正确的位置,方法是计算每组4或5个字母有多少个品牌,然后做与放入's'相同的操作。 But it doesn't work. 但这是行不通的。

Is there any way I can maybe tell the header to insert only on the first run of the loop? 有什么方法可以告诉标题仅在循环的第一次运行时插入?

Try this 尝试这个

$ascci_val =  ord( strtolower(sub_str($name, 0, 1)) );
if( ($ascci_val >= 97) && ($ascci_val <= 100) ){ 
  // brand name stats with a letter between A-D / a-d
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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