Home > Enterprise >  Order alphabetically SimpleXML array by attribute
Order alphabetically SimpleXML array by attribute

Time:05-02

I need a bit of help ordering a SimpleXML array in an alphabetical order using one of it's attribute ($url). I have the following code that generate a page:

<?php
$xml = simplexml_load_file($xml_url);
$ids = array();

foreach($xml->list as $id) {
   $ids[] = $id;
}

//It works but randomize instead of sorting alphabetically
usort($ids, function ($a, $b) {
   return strnatcmp($a['url'], $b['url']);
});

foreach ($ids as $id) {
   PopulatePage($id);
}

function PopulatePage($id) {
   $url = $id->url;
   $img = $id->img;
   //OTHER CODES TO GENERATE THE PAGE
}?>

QUESTION RESOLVED!

CodePudding user response:

There is no conversion needed, you already have an array which you can sort, you just need to understand how usort callbacks work. Each of the items in your $ids array is a SimpleXMLElement object, and each time your callback is run, it will be given two of those objects to compare. Those objects will be exactly the same as in the existing PopulatePage function, so accessing the URL needs to happen exactly as it does there ($url = $id->url;) not using a different notation ($id['url']).

To make it more explicit, let's write a named function with lots of clear variable names:

function CompareTwoIds(SimpleXMLElement $left_id, SimpleXMLElement $right_id): int {
    $left_url = $left_id->url;
    $right_url = $right_id->url;
    return strncatcmp($left_url, $right_url);
}

Now you can test calling that function manually, and use it as the callback when you're happy:

usort($ids, 'CompareTwoIds');

Once you're comfortable with the principles, you may decide to skip the extra verbosity and just write this, which is completely equivalent:

usort($ids, fn($a,$b) => strncatcmp($a->url, $b->url));
  • Related