开发者

Problem with sort and then output

开发者 https://www.devze.com 2023-01-31 01:11 出处:网络
Im using the PHP below to generate some HTML output: <?php $url = \"images.xml\"; $xmlstr = file_get_contents($url);

Im using the PHP below to generate some HTML output:

<?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->开发者_如何学Gosource;
    $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>";
}
?>

If I change the code here:

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

I get the image link 3 times, which is correct because there are 3 records in the XML. But I get 12 copies of the text Item.

Why is this happening?


You're putting each attribute in a new row in the array. Try this:

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消