tags:

views:

124

answers:

3

Hi ,

I neeed to order my loop by the id

my xml doc looks like this

<gig id="16">
        <date>Fri. 23rd Apr</date>
        <venue>Sneaky Pete's</venue>
        <area>Edinburgh</area>
        <telephone>www.ticketweb.co.uk</telephone>  
        <price>£10</price>
        <time>Time TBA</time>
    </gig>  

So as you can see I need to order my string by this id

my code for the output is

<?php 
foreach ($xml->gig as $dateof){
echo '<tr><td><img src="images/arrow.jpg" /></td><td width="200px" class="loop-Date">' . $dateof->date . '</td><td width="700px">' . $dateof->venue . '</td></tr>';
}
?>

Hope this makes sense

A: 

There's no order-by option in (standard) xpath, but in xsl(t) there is e.g. <xsl:sort>

VolkerK
+1  A: 
$array = array();
foreach ($xml->gig as $gig) {
   $id = (int)$gig->attributes()->id;
   $array[$id] = $gig;
}

Order by ID: ksort($array);

foreach ($array as $id => $gig) {
   echo '<tr><td><img src="images/arrow.jpg" /></td><td width="200px" class="loop-Date">' . (string)$gig->date . '</td><td width="700px">' . (string)$gig->venue . '</td></tr>';
}

Never forget to cast the SimpleXMLObjects to Strings (or Integers, ...).

r3zn1k
You were faster than me :) BTW: In the second line of the second block you need to replace `$dateof` into `$gig`.
Veger
Thanks Veger for that.Thanks r3zn1k for your help :-)
Oliver Bayes-Shelton
I cannot seem to get it working it just display's blank , no error's just looks like it's not getting the values ?????
Oliver Bayes-Shelton
The attribute should be read via array access, no need to call attributes() -- `$id = (int) $gig['id'];`
Josh Davis
Could you explain a little josh :)
Oliver Bayes-Shelton
Instead of using `$gig->attributes()->id` you can use `$gig['id']`. That's how SimpleXML was supposed to be used in the first place. attributes() was added later, to deal with namespaced attributes.
Josh Davis
I didn't test it. Use "print_r($array);" to display the content of the array. What does this command return?
r3zn1k
It's working now , How could I change the order to desc ?
Oliver Bayes-Shelton
use "krsort" instead of "ksort"
r3zn1k
A: 

I often see requests to sort XML elements, generally based on the result of an XPath query.

For that purpose I've written a method, sortedXPath(), for SimpleDOM. It has the same signature as array_multisort() except that the first argument is an XPath expression and instead of using array keys it uses XPath expressions. For example, here's how to retrieve all <gig/> elements, sorted by their id attribute:

include 'SimpleDOM.php';

$gigs = simpledom_load_string(
    '<gigs>
        <gig id="16">
            <date>Fri. 23rd Apr</date>
        </gig>
        <gig id="15">
            <date>Fri. 16th Apr</date>
        </gig>
    </gigs>'
);

foreach ($gigs->sortedXPath('//gig', '@id') as $gig)
{
    echo 'gig id ', $gig['id'], ' - date: ', $gig->date, "\n";
}
Josh Davis