问题
I have this simplexml array which i managed to get working from examples on google. now i have to sort the array.
this is what i have.
$url = 'http://api.trademe.co.nz/v1/Member/2128687/Listings/All.xml';
$xml = simplexml_load_file($url);
foreach($xml->List->Listing as $list){
echo $list->EndDate;
echo '<br/>';
}
everything works as it should like that. i want to sort it by closest to end date.
ive tried all the examples i can find and i just keep getting white screen of nothing.
please help!
回答1:
using usort
$xml = simplexml_load_file($url);
$listingarray = (array)$xml->List;
$listingarray = $listingarray['Listing'];
function compare($obj1,$obj2)
{
$time1 = strtotime($obj1->EndDate);
$time2 = strtotime($obj2->EndDate);
if($time1 == $time2)
return 0;
return ($time1 > $time2 ? -1 : 1);
}
usort($listingarray,'compare');
foreach($listingarray as $list)
{
echo $list->EndDate . '<br />';
}
?>
if your php version >= 5.3 you can write the compare function inline as a parameter..
usort($listingarray,function($obj1,$obj2)
{
$time1 = strtotime($obj1->EndDate);
$time2 = strtotime($obj2->EndDate);
if($time1 == $time2)
return 0;
return ($time1 > $time2 ? -1 : 1);
});
回答2:
function cmp($a, $b)
{
$a = strtotime($a->EndDate);
$b = strtotime($b->EndDate);
if ($a == $b)
{
return 0;
}
return ($a < $b) ? -1 : 1;
}
uasort($xml->List->Listing, 'cmp');
print_r($array);
来源:https://stackoverflow.com/questions/8285029/sort-simplexml-array