开发者

return the image with the lowest views with xml and php?

I am trying to create a weighted banner system for my website.

This is my XML:

<banners>
    <images>
        <src>banners/ad_1.png</src>
        <alt>Banner ad 1</alt>
        <views>9</views>
    </images>
    <images>
        <src>banners/ad_2.png</src>
        <alt>Banner ad 2</alt>
        <views>9</views>
    </images>
</banners>

I want to display the image with the lowest view. 开发者_开发技巧Once I have that image, increment the view to show that the banner has been shown.

I don't want to use simpleXML. All the dom manipulation will directly be using this $dom variable:

$dom = new DOMDocument();
$dom->load($file_name);

I have been at this for over 3 hours and my code just keeps getting bigger and bigger. I have figured out how to increment it and place it back into the XML file. I just don't know how to pull the image that has the lowest views for display.

Any help, even ideas would be GREATLY appreciated!


$images = $dom->getElementsByTagName("images"); //Grab all image nodes
$views = array(); //Set up array for src and viewcount data
foreach($images as $image){ //Loop through all image nodes
   $src = $image->getElementsByTagName("src")->nodeValue; //Get the src
   $views[$src] = $image->getElementsByTagName("views")->nodeValue; //Add the viewcount to the array and use src as the array key
}
asort($views); //Sort the array by viewcount (low->high)
$src = array_keys($views); //Extract keys (or src)

$lowestViews = $views[0]; //Var for lowest number of views
$lowestSrc = $src[0]; //Var for the src of the lowest viewed image

I hope that helps! Sorry for mega commenting. Got bored.


You should consider using a database for storing your ads so that you can query for this data. With XML, I don't know much of a better way than reading the entire file into an array and then sorting the array at that point, but with MySQL or any other SQL-style database, you can simply run:

SELECT * FROM ads ORDER BY views LIMIT 1;

And that would get you the lowest view count. Updating that view count is easy (and concurrency-safe) too:

UPDATE ads SET views = views + 1 WHERE id = <ID>;

In short, a relational database lets you query your data, whereas an XML file (at least, in its raw form) only lets you store it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜