php foreach - 如何组合多个网址

时间:2011-03-18 03:08:14

标签: php foreach

我如何组合这些只为每个循环使用一个。为我想要添加的每个额外网址复制和粘贴新代码很痛苦。再加上效率不高。

$urlone = json_decode(file_get_contents('https://graph.facebook.com/100404580017882/posts'));
$urltwo = json_decode(file_get_contents('https://graph.facebook.com/100404590017836/posts'));

foreach($urlone->data as $post) { 
       echo $post->message, PHP_EOL . "<br>"; 
       if(++$counter >= 1) 
       { 
          break; 
       } 
    } 

foreach($urltwo->data as $post) { 
       echo $post->message, PHP_EOL . "<br>"; 
       if(++$counter >= 1) 
       { 
          break; 
       } 
    } 

4 个答案:

答案 0 :(得分:0)

array_merge()是您的解决方案。

$urlone = json_decode(file_get_contents('https://graph.facebook.com/100404580017882/posts'));
$urltwo = json_decode(file_get_contents('https://graph.facebook.com/100404590017836/posts'));

$data = array_merge($urlone->data, $urltwo->data);

foreach($data as $post) { 
    echo $post->message, PHP_EOL . "<br>"; 
    if(++$counter >= 1) 
    { 
        break; 
    } 
}

答案 1 :(得分:0)

把它放在一个函数中可能是要走的路,因为你不能保证它返回的内容都有相同的长度。

function fetch_posts($url){
  $obj = json_decode(file_get_contents($url));
  foreach($obj->data as $post) { 
    echo $post->message, PHP_EOL . "<br>"; 
    if(++$counter >= 1) { 
      break; 
    } 
  }
}

答案 2 :(得分:0)

这就是以下功能:

function echo_messages($url)
{
     $data = json_decode(file_get_contents($url));
     foreach($data->data as $post) 
     { 
       echo $post->message, PHP_EOL . "<br>"; 
     } 
     //Wasn't sure what the counter was for, looks like it would just break after the first message was echoed.
}

echo_messages('https://graph.facebook.com/100404580017882/posts');
echo_messages('https://graph.facebook.com/100404590017836/posts');

顺便说一句,如果你只是想输出最新的帖子,那么在foreach循环中执行它并且在第一个之后就破坏是错误的方式。你应该用$variable->data[0]->message之类的东西直接解决它。或者,您可以修改上面的代码以构建可设置的限制,以显示最大显示的消息数,如:

function echo_messages($url,$max = 1)
{
     $data = json_decode(file_get_contents($url));
     $counter = 0;
     foreach($data->data as $post) 
     { 
       echo $post->message, PHP_EOL . "<br>";
       $counter++;
       if($counter >= $max)
       {
            return true;
       }
    } 
}

echo_messages('https://graph.facebook.com/100404580017882/posts',5); //Display last 5 posts from this one
echo_messages('https://graph.facebook.com/100404590017836/posts'); //Display last post from this one

答案 3 :(得分:0)

创建或获取要以此方式处理的url数组,然后对数组中的每个项使用函数:

$urls = array('https://graph.facebook.com/...', 'https://graph.facebook.com/....');

function printPosts($url){
    echo "<div class='posts'>";
    $posts = json_decode(file_get_contents($url));

    foreach($posts->data as $post) { 
        echo $post->message, PHP_EOL . "<br>";
        //etc
    } 
    echo "</div>\n";
}