传递数组值时遇到问题

时间:2011-06-13 13:56:40

标签: php

我正在构建一个PHP程序,它基本上只从我的twitter feed中抓取图像链接并在页面上显示它们,我有3个组件,我已经设置了所有可以自行工作。

第一个组件是twitter oauth组件,它抓取推文文本并创建一个数组,这本身就可以正常工作。

第二个是处理推文的函数,只返回包含图像链接的推文,这也很好。

当处理链接并显示图像时,程序在第三部分中出现故障,我自己运行此问题并没有问题,而且我尝试解决问题时看起来它在$ images()时出现故障;数组,因为该数组为空。

我确定我犯了一个愚蠢的错误,但我一直试图找到这一天超过一天,似乎无法修复它。任何帮助都会很棒!谢谢你们!

代码:

<?php

if ($result['socialorigin']== "twitter"){
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($result['oauthtoken'], $result['oauthsecret']);
$tweets = $twitterObj->get('/statuses/home_timeline.json',array('count'=>'200'));

         $all_tweets = array();
         $hosts  = "lockerz|yfrog|twitpic|tumblr|mypict|ow.ly|instagr";



         foreach($tweets as $tweet) {

         $twtext = $tweet->text;

         if(preg_match("~http://($hosts)~", $twtext)){

         preg_match_all("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise", $twtext, $matches, PREG_PATTERN_ORDER);

         foreach($matches[0] as $key2 => $link){

         array_push($all_tweets,"$link");

         }

         }

         }
function height_compare($a1, $b1)
{
    if ($a1 == $b1) {
        return 0;
    }
    return ($a1 > $b1) ? -1 : 1;
}

foreach($all_tweets as $alltweet => $tlink){
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to supress errors
@$doc->loadHTMLFile($tlink);

// Get all images
$images_list = $doc->getElementsByTagName('img');

$images = array();
foreach($images_list as $image) {

  // Get the src attribute
  $image_source = $image->getAttribute('src');

  if (substr($image_source,0,7)=="http://"){
  $image_size_info = getimagesize($image_source);

  $images[$image_source] = $image_size_info[1];
  }
}



// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);

echo "<img src='$mainimg' />";


 }
 print_r($all_tweets);
 print_r($images);

}

1 个答案:

答案 0 :(得分:1)

更改获取实际图像的for循环,将images数组移出for循环。这样可以防止循环每次都清除它。

  $images = array();
foreach($all_tweets as $alltweet => $tlink){
  $doc = new DOMDocument();
  // Okay this is HTML is kind of screwy
  // So we're going to supress errors
  @$doc->loadHTMLFile($tlink);

  // Get all images
  $images_list = $doc->getElementsByTagName('img');    
  foreach($images_list as $image) {

    // Get the src attribute
    $image_source = $image->getAttribute('src');

    if (substr($image_source,0,7)=="http://"){
      $image_size_info = getimagesize($image_source);

      $images[$image_source] = $image_size_info[1];
    }
  }

  // Do a numeric sort on the height
  uasort($images, "height_compare");
  $tallest_image = array_slice($images, 0,1);
  $mainimg = key($tallest_image);

  echo "<img src='$mainimg' />";
}
相关问题