你的数组很好。接下来你需要的是usort
:
$xml=simplexml_load_string(<<<XML
<?xml version="1.0"?>
<calender>
<task>
<date>00/00/0000</date>
<title>My Birthday</title>
<description>Today is my birthday!</description>
</task>
<task>
<date>04/08/2013</date>
<title>test</title>
<description>swdefswde</description>
</task>
<task>
<date>04/02/2013</date>
<title>test</title>
<description>test</description>
</task>
<task>
<date>04/01/2013</date>
<title>egfwe</title>
<description>wefwef</description>
</task>
<task>
<date>04/03/2013</date>
<title>ssdv</title>
<description>ssdvs</description>
</task>
</calender>
XML
);
$arr=array();
foreach($xml->task as $aTask)
{
$arr[]=$aTask;
}
//print_r($arr);
/* uncomment the above line to debug */
usort($arr,function($a,$b){
return strtotime($a->date)-strtotime($b->date);
});
//print_r($arr);
/* uncomment the above line to debug */
$xml=simplexml_load_string(<<<XML
<?xml version="1.0"?>
<calender>
</calender>
XML
);
foreach($arr as $aTask)
{
$tTask=$xml->addChild($aTask->getName());
$tTask->addChild($aTask->date->getName(),(string)$aTask->date);
$tTask->addChild($aTask->title->getName(),(string)$aTask->title);
$tTask->addChild($aTask->description->getName(),(string)$aTask->description);
}
echo $xml->asXML();
回显的 XML(手动格式化以使其看起来更好):
<?xml version="1.0"?>
<calender>
<task>
<date>00/00/0000</date>
<title>My Birthday</title>
<description>Today is my birthday!</description>
</task>
<task>
<date>04/01/2013</date>
<title>egfwe</title>
<description>wefwef</description>
</task>
<task>
<date>04/02/2013</date>
<title>test</title>
<description>test</description>
</task>
<task>
<date>04/03/2013</date>
<title>ssdv</title>
<description>ssdvs</description>
</task>
<task>
<date>04/08/2013</date>
<title>test</title>
<description>swdefswde</description>
</task>
</calender>
需要 PHP >= 5.3
Live demo