迭代数组并返回前10个结果


Iterating through an array and returning first 10 results

所以我试图迭代似乎是json提要,我使用以下代码来获得所有数组结果,然而,我如何返回特定项,让我们说前6或10 ?

<?php 
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$headers = array('Content-Type: application/json');
$url = 'https://weedmaps.com/api/web/v1/listings/green-valley-medicinal/menu?show_unpublished=false&type=dispensary';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch); 
curl_close($ch);
$menu_data = json_decode($result, true);
            foreach($menu_data['categories'] as $menu_item){
            foreach ($menu_item['items'] as $item) {
      echo '<article class="col-sm-6 col-md-4">';
      echo isset($item['image_url']) ? '<img class="media-object menu-item-photo" height="120" width="120" src="'.$item['image_url'].'">' : '<img class="media-object menu-item-photo" height="120" src="images/mmjicon.png">';
      echo '<h2>'.$item['name'].'</h2>';
      echo '<p>'.$item['body'].'</p>';
      echo '</article>';
      }
    }
    ?>

任何帮助都将非常感激。干杯!

有多种方法可以做到这一点。

保持foreach循环,添加一个计数,增加它,并在达到10时终止循环。

$count = 0;
foreach(...) {
    ...
    if (++$count >= 10) break;
}

如果您无法控制正在检索的数据的数量,您可以在foreach中使用$counter。

$your_limit = 6;
$counter = 0;
foreach($menu_data['categories'] as $menu_item){
    if ( ++$counter > $your_limit ){
        break;
    }        
    foreach ($menu_item['items'] as $item) {
      echo '<article class="col-sm-6 col-md-4">';
      echo isset($item['image_url']) ? '<img class="media-object menu-item-photo" height="120" width="120" src="'.$item['image_url'].'">' : '<img class="media-object menu-item-photo" height="120" src="images/mmjicon.png">';
      echo '<h2>'.$item['name'].'</h2>';
      echo '<p>'.$item['body'].'</p>';
      echo '</article>';
      }
    }