2011-02-19 91 views
0

我正在使用SimpleXML從公共提要@ Flickr中提取圖像。我希望把所有拉到圖像到一個數組中,我已經做了:通過foreach創建數組

$images = array(); 
foreach($channel->item as $item){ 
    $url = $path->to->url; 
    $images[] = $url; 
} 

從這個話,我可以附和了所有的圖像使用:

foreach($images as $image){ 
    //output image 
} 

然後我決定我想有圖像標題,以及用戶,所以我認爲我會用:

$images = array(); 
foreach($channel->item as $item){ 
    $url = $path->to->url; 
    $title = $path->to->title; 
    $images[$title] = $url; 
} 

我想用我$image['name of title']可輸出爲標題的URL,這將意味着,但它提供了一個非法的偏移誤差,當我る這個..只會有標題和網址,但不是用戶。

谷歌上搜索了一下我念你不能在數組鍵​​使用_後,但我嘗試使用:

$normal = 'dddd'; 
$illegal = ' de___eee'; 
$li[$normal] = 'Normal'; 
$li[$illegal] = 'Illegal'; 

而這種輸出權,排除_是在數組中的鍵非法(..我想) 。

所以現在我真的很困惑爲什麼它不會運行,當我在玩時使用print_r()我注意到數組中的一些SimpleXML對象,這就是爲什麼我認爲這是給出錯誤。

理想的輸出將在格式的數組:

$image = array(0 => array('title'=>'title of image', 
          'user'=>'name of user', 
          'url' =>'url of image'), 
       1 => array(....) 
     ); 

但我真的難倒我怎麼會從foreach環路構成本,鏈接引用以及其他問題(couldn」 t找到任何),歡迎。

回答

3
$images = array(); 
foreach ($channel->item as $item){ 
    $images[] = array(
     'title' => $item->path->to->title, 
     'url' => $item->path->to->url 
    ); 
} 

foreach ($images as $image) { 
    echo "Title: $image[title], URL: $image[url]\n"; 
} 
+0

謝謝你,我覺得很愚蠢。 – Daniel 2011-02-19 04:22:14

0

下劃線不禁止數組鍵,您可能會遇到的唯一問題符號,即標題一些時間重疊,你可能數組中失去一些項目。最正確的方法是deceze example

如果你喜歡關聯數組,你可以使用圖像路徑作爲數組鍵和標題作爲值。