【问题标题】:PHP: How do I limit the amount of results in an array [duplicate]PHP:如何限制数组中的结果数量[重复]
【发布时间】:2017-08-29 04:32:08
【问题描述】:

我正在从 Twitter API 中提取趋势。我最终得到一个包含 42 个项目的数组。我可以很好地打印我想要的元素,但是我想将元素的数量限制为 5 个而不是 42 个。

这是返回数据的截图:

这是我的 foreach 循环,它抓取我想要的元素(名称):

foreach ($string[0]['trends'] as $trend) {

    echo $trend['name']."<br />";

}

如何只打印前 5 个元素([name])?

【问题讨论】:

    标签: php


    【解决方案1】:

    对于当前场景,可以使用数组键:-

    foreach ($string[0]['trends'] as $key=>$trend) {
       if($key<5){
         echo $trend['name']."<br />";
       }
    }
    

    但如果数组索引不是像0,1,2,3,...这样的自动递增格式> 那么你就可以使用计数器了。

    $counter = 0;
    foreach ($string[0]['trends'] as $trend) {
       if($counter<5){
         echo $trend['name']."<br />";
       }
      $counter++;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 2021-11-20
      • 2010-11-20
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多