如何将它们组合在一起,以便只使用一个for each循环。这是一个痛苦的复制和粘贴新的代码为每个额外的网址,我想添加。另外,它的效率不是很高。
$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;
}
} 发布于 2011-03-18 11:18:35
这就是创建函数的目的:
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');顺便说一句,如果你只是想输出最新的post,那么在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发布于 2011-03-18 11:11:58
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;
}
}发布于 2011-03-18 11:14:19
把它放在一个函数中可能是可行的,因为你不能保证无论它返回什么都有相同的长度。
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;
}
}
}https://stackoverflow.com/questions/5347633
复制相似问题