zoukankan      html  css  js  c++  java
  • foreach的用法

    案例1:The item attribute

    <?php
    $arr = array(1000, 1001, 1002);
    $smarty->assign('myArray', $arr);
    ?>

    Template to output $myArray in an un-ordered list

    <ul>
    {foreach from=$myArray item=foo}
        <li>{$foo}</li>
    {/foreach}
    </ul>

    The above example will output:

    <ul>
        <li>1000</li>
        <li>1001</li>
        <li>1002</li>
    </ul>

    案例2:Demonstrates the item and key attributes

    <?php
    $arr = array(9 => 'Tennis', 3 => 'Swimming', 8 => 'Coding');
    $smarty->assign('myArray', $arr);
    ?>

    Template to output $myArray as key/val pair, like PHP's foreach.

    <ul>
    {foreach from=$myArray key=k item=v}
       <li>{$k}: {$v}</li>
    {/foreach}
    </ul>

    The above example will output:

    <ul> <li>9: Tennis</li> <li>3: Swimming</li> <li>8: Coding</li> </ul>

     

    案例3:{foreach} with associative item attribute

    <?php
    $items_list = array(23 => array('no' => 2456, 'label' => 'Salad'),
                        96 => array('no' => 4889, 'label' => 'Cream')
                        );
    $smarty->assign('items', $items_list);
    ?>

    Template to output $items with $myId in the url

    <ul>
    {foreach from=$items key=myId item=i}
      <li><a href="item.php?id={$myId}">{$i.no}: {$i.label}</li>
    {/foreach}
    </ul>

    The above example will output:

    <ul>
      <li><a href="item.php?id=23">2456: Salad</li>
      <li><a href="item.php?id=96">4889: Cream</li>
    </ul>

    案例4: {foreach} with nested item and key

    <?php
     $smarty->assign('contacts', array(
                                 array('phone' => '1',
                                       'fax' => '2',
                                       'cell' => '3'),
                                 array('phone' => '555-4444',
                                       'fax' => '555-3333',
                                       'cell' => '760-1234')
                                 ));
    ?>

    The template to output $contact.

    {foreach name=outer item=contact from=$contacts}
      <hr />
      {foreach key=key item=item from=$contact}
        {$key}: {$item}<br />
      {/foreach}
    {/foreach}

    The above example will output:

    <hr />
      phone: 1<br />
      fax: 2<br />
      cell: 3<br />
    <hr />
      phone: 555-4444<br />
      fax: 555-3333<br />
      cell: 760-1234<br />

    小结:

    记住常用方法,并能灵活运动,举一反三。

    没必要所有的都会使用,会使用常用的就可以了。

  • 相关阅读:
    leetcode第四题
    解决Hystrix主线程结束,子线程拿不到request
    RabbitMQ如何保证消息的顺序性+解决消息积压+设计消息队列中间件
    RabbitMQ 如何保证消息不丢失?
    redis布隆过滤器的使用
    PageHelper自定义count
    mysqlbinlog 工具分析binlog日志
    linuxubuntu常用命令
    MySQL 常用命令
    Ubuntu 16.04 安装 Apache, MySQL, PHP7
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/2953764.html
Copyright © 2011-2022 走看看