0

I'm trying to order my XML by date but code doesn't work well. Here is my code

$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;
});

I did like this

foreach($arr as $aTask)
{
    $data1 = $aTask->cadastro;
}

But is not returning by date, it is returning this 03/08/2015 18:22 24/11/2015 11:16 22/10/2015 17:36

Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
  • show some sample dates, and check that DateTime is successfully parsing them. you're just assuming success right now. – Marc B Dec 03 '15 at 17:04
  • Possible duplicate of [sorting the table fields using simple XML and xpath](http://stackoverflow.com/questions/15604459/sorting-the-table-fields-using-simple-xml-and-xpath) – michi Dec 03 '15 at 17:09
  • i've tried a lot of examples but none of them worked well – Leonardo Raposo Dec 03 '15 at 17:14
  • I've just tried to use @michi http://stackoverflow.com/questions/15604459/sorting-the-table-fields-using-simple-xml-and-xpath and it didn't work either – Leonardo Raposo Dec 03 '15 at 17:27

1 Answers1

0

I think $a and $b are of type SimpleXMLElement and $a['cadastro'] and $b['cadastro'] are null.

So you are instantiating your DateTime's like this new DateTime(null) and that will match this line: if ($ad == $bd) { and your array will not get sorted.

Maybe you can do it like this:

$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;
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70