我正在尝试按日期排序我的XML,但是代码不能很好地工作。这是我的密码
$xml = simplexml_load_file ('http://xml.dsautoestoque.com/?l=09086369000133');
$arr=array();
foreach($xml->veiculo as $aTask)
{
$arr[]=$aTask;
}
usort($arr, function($a, $b) {
$ad = new DateTime($a['cadastro']);
$bd = new DateTime($b['cadastro']);
if ($ad == $bd) {
return 0;
}
return $ad > $bd ? 1 : -1;
});我确实喜欢这个
foreach($arr as $aTask)
{
$data1 = $aTask->cadastro;
}但不是按日期返回,而是返回这03/08/2015 18:22 24/11/2015 11:16 22/10/2015 17:36
发布于 2015-12-03 18:08:40
我认为$a和$b是SimpleXMLElement型,$a['cadastro']和$b['cadastro']是null型。
因此,您正在实例化日期时间,就像这个new DateTime(null),这将与这一行相匹配:if ($ad == $bd) {和您的数组不会被排序。
也许你可以这样做:
$xml = simplexml_load_file ('http://xml.dsautoestoque.com/?l=09086369000133');
$arr = array();
foreach ($xml->veiculo as $aTask) {
$arr[] = $aTask;
}
usort($arr, function ($a, $b) {
$ad = DateTime::createFromFormat('d/m/Y H:i', $a->cadastro->__toString());
$bd = DateTime::createFromFormat('d/m/Y H:i', $b->cadastro->__toString());
if ($ad == $bd) {
return 0;
}
return $ad > $bd ? 1 : -1;
});https://stackoverflow.com/questions/34071859
复制相似问题