2017-06-21 4 views
1

私はハッシュタグに基づいてInstagramから画像を表示するために、以下のスクリプトを使用しています。それは完璧に動作し、Instagramによって使用可能なすべての画像をリストアップします - 最大20画像。PHP:ループ - 最大アイテムを追加する方法

しかし、私は少ない、例えば10または12の画像を表示することができるようにしたいと思います。

foreachループがすべてのアイテムをループしないように、最大​​アイテム値を保持する変数を追加するにはどうすればよいですか?

PHP:あなたは1-12イメージして、使用しないで他のカウンターを表示したい場合は

<?php 
    // Enter hashtag; 
    $hashtag = "nofilter"; 
    $url = "https://www.instagram.com/explore/tags/".$hashtag."/"; 
    $instagram_content = file_get_contents($url); 
    preg_match_all('/window._sharedData = (.*)\;\<\/script\>/', $instagram_content, $matches); 
    $txt = implode('', $matches[1]); 
    $json = json_decode($txt); 

    foreach ($json->entry_data->TagPage{0}->tag->media->nodes AS $item) { 
     echo "<div class='imgbox'><a href='http://instagram.com/p/".$item->code."' target='_blank'><img class='hashtag' src='" . $item->display_src . "' alt=''></a></div>"; 
    } 
    ?> 
+0

カウンターのような "何らかの変数"テル? – j08691

+0

はい、次のようになります。 $ noOfImages = 12; - foreachは12個の画像だけをループします。 – Meek

答えて

0

。このコードでは、counterが12より大きい場合、ループは中断されるので、1〜12の画像だけが表示されます。

$count = 0; 
foreach ($json->entry_data->TagPage{0}->tag->media->nodes AS $item) { 
    if($count >= 12){ 
     break; 
    } 
    echo "<div class='imgbox'><a href='http://instagram.com/p/".$item->code."' target='_blank'><img class='hashtag' src='" . $item->display_src . "' alt=''></a></div>"; 
$count++;  
} 
+0

これは本当に好きです。どうもありがとう。 – Meek

+0

あなたは大歓迎で、 –

+0

@Meekをお持ちであれば、私の投票をすることができます。 –

0

シンプルです。カウンタ変数を使用します。

$loop_count = 0; 
$max = 12; 
foreach ($things as $thing) { 
    if ($loop_count >= $max) { 
     break; 
    } 

    // Do loop logic here 

    $loop_count++; 
} 
0

forループ使用します。配列が数インデックス化されている場合は、この作品あなたのケースで実装

foreach ($list as $index => $value) { 
    if ($index > 12) break; 
    //do something 
} 

は以下の通りである

for ($i = 0; $i < 12; $i++) { 
    $item = $json->entry_data->TagPage{0}->tag->media->nodes[$i]; 
    echo "<div class='imgbox'><a href='http://instagram.com/p/".$item->code."' target='_blank'><img class='hashtag' src='" . $item->display_src . "' alt=''></a></div>"; 
} 
0

を:

<?php 
    // Enter hashtag; 
    $hashtag = "nofilter"; 
    $url = "https://www.instagram.com/explore/tags/".$hashtag."/"; 
    $instagram_content = file_get_contents($url); 
    preg_match_all('/window._sharedData = (.*)\;\<\/script\>/', $instagram_content, $matches); 
    $txt = implode('', $matches[1]); 
    $json = json_decode($txt); 

    foreach ($json->entry_data->TagPage{0}->tag->media->nodes AS $index => $item) { 
     if ($index > 12) break; 
     echo "<div class='imgbox'><a href='http://instagram.com/p/".$item->code."' target='_blank'><img class='hashtag' src='" . $item->display_src . "' alt=''></a></div>"; 
    } 
    ?> 
関連する問題