2010-12-18 72 views
0

林下面生成一些HTML輸出:問題與使用PHP進行排序,然後輸出

<?php 

$url = "images.xml"; 
$xmlstr = file_get_contents($url); 
$xml = new SimpleXMLElement($xmlstr); 
$images = array(); 
$ids = array(); 

foreach ($xml->image as $image) { 

    $images[]['id'] = $image -> id; 
    $images[]['link'] = $image->href; 
    $images[]['src'] = $image->source; 
    $images[]['title'] = $image->title; 
    $images[]['alt'] = $image->alt; 
    $ids[] = $image -> id; 
} 

array_multisort($ids, SORT_ASC, $images); 

foreach ($images as $image){ 
    echo "<a href='".$image['link']."'><img src='".$image['src']."' alt='".$image['alt']."' title='".$image['title']."' /></a>"; 
} 
?> 

如果我改變這裏的代碼:

foreach ($images as $image){ 
echo $image['link']; 
    echo "Item"; 
} 

我得到的圖像鏈接3倍,這是正確的,因爲XML中有3條記錄。但我得到12個文本項目的副本。

這是怎麼發生的?

+1

我認爲你需要一點更精確的關於不正確的輸出 - 可能你的XML的一個片段將是有益的了。根據我所知道的,你說的是'for'循環可以運行3次或12次(或者可能同時運行兩次?!?)。 – Basic 2010-12-18 15:06:35

+0

其他人都在下面瞭解。 – CLiown 2010-12-18 15:13:03

回答

3

您正在將每個屬性放入數組的新行中。 試試這個:

foreach ($xml->image as $image) 
{ 
    $images[] = array(
     'id' => $image->id, 
     'link' => $image->href, 
     'src' => $image->source, 
     'title' => $image->title, 
     'alt' => $image->alt 
    ); 

    $ids[] = $image -> id; 
} 
相關問題