【问题标题】:get the first 6 items获取前 6 个项目
【发布时间】:2013-05-22 07:34:40
【问题描述】:

我有一个小的 php 代码。此代码获取博客项目的标题。但我对这段代码有疑问。

我该怎么做。最近6个冠军的回升?

<ul class="blog-list">
    <?php foreach ($siblings as $sibling) : ?>
    <li><a href="<?php echo get_permalink($sibling->ID); ?>" data-nav-position="fade"><?php echo get_the_title($sibling->ID); ?></a></li>
    <?php endforeach; ?>
</ul>

感谢您的帮助

【问题讨论】:

标签: php wordpress foreach


【解决方案1】:

如果你拿一些数组元素不要使用foreach(见每个这个词?)。

改用for循环

for($i = 0; $i < 6; ++$i){
  $sibling = $siblings[$i];

获得前 6 个或

for($i = count($siblings); $i > count($siblings) - 6; --$i){
  $sibling = $siblings[$i];

得到最后六个(以相反的顺序)

编辑

如果数组键不是整数或其中有一些空范围,这将不起作用。然后您可以按照其他答案中的建议使用array_slice()array_pop() 六次。

【讨论】:

    【解决方案2】:

    最简单的选项,您的更改不多。

    <ul class="blog-list">
        <?php $i = 0; ?>
        <?php foreach ($siblings as $sibling) : ?>
        <li><a href="<?php echo get_permalink($sibling->ID); ?>" data-nav-position="fade"><?php echo get_the_title($sibling->ID); ?></a></li>
        <?php if(++$i>=6) break; ?>
        <?php endforeach; ?>
    </ul>
    

    【讨论】:

      【解决方案3】:

      使用 array_slice 获取最后六个项目,然后循环遍历它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        • 2021-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多