【问题标题】:fetching items from array and putting it on a loop从数组中获取项目并将其放在循环中
【发布时间】:2012-02-12 20:30:26
【问题描述】:

我正在尝试从数组中获取项目。这就是我的列表的样子。

这是我的物品的样子

fruits[apple] = 'apple';
fruits[grapes] = 'grapes';
fruits[banana] = 'banana';

animals[dog] = 'dog';
animals[cat] = 'cat';
....

我的循环应该是这样的。

<ul>
   <li> <a href="fruits/<?php echo $fruits ?>"><?php echo $fruits ?></a> </li>
</ul>

【问题讨论】:

    标签: php arrays loops while-loop


    【解决方案1】:
    if(is_array($fruits) && count($fruits) > 0){
        echo "<ul>\n";
        foreach($fruits as $fruit){
            echo "<li><a href=\"fruits/".$fruit."\">".$fruit."</a></li>\n";
        }
        echo "</ul>\n";
    } else {
        echo "No Fruits :(";
    }
    

    简单!

    你也可以对动物做同样的事情......

    【讨论】:

    • 添加了简单的检查看看是否有东西,否则会弹出错误
    • 这对我有用!谢谢... prodigitalson 也是一个好方法。
    【解决方案2】:

    MrJ 已经给了你答案,但我发布了这个,所以你可以看到替代和 IMO 更好、更清晰的语法:

    <?php if(count($fruits)): // dont output unless we actually have fruits! ?>
      <ul>
      <?php foreach($fruits as $fruit): ?>
         <li><a href="fruits/<?php echo $fruit ?>"><?php echo $fruit ?></a></li>
      <?php endforeach; ?>
      </ul>
    <?php endif; ?> 
    

    更好的是使用printf 来创建链接,这样我们就不必一直切换进出php,同时仍然避免疯狂的字符串连接来生成html:

    <?php if(count($fruits)): // dont output unless we actually have fruits! ?>
      <ul>
      <?php foreach($fruits as $fruit): ?>
         <li><?php printf('a href="%s">%s</a>', $fruit, $fruit) ?></li>
      <?php endforeach; ?>
      </ul>
    <?php endif; ?> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2015-08-12
      相关资源
      最近更新 更多