Question

I am attempting to sort a list of nodes alphabetically, before echoing them out in SimpleXML. I am using a usort function similar to the one referenced here:

Sorting Results returned by SimpleXML, and Xpath in PHP

Here is my code:

$xQuery = $xml->comiclist->comic;

function cmp ($a, $b) {
     return strcmp(
         $a->mainsection->series->sortname, 
         $b->mainsection->series->sortname
     ); 
}

usort($xQuery, "cmp");

foreach ($xQuery as $comic) :

The issue is that it only seems to be partially working. Most of the items are grouped together correctly but, some are completely out of place. As you can see from the function, each $comic node is being sorted by its child "mainsection->series->sortname".

Here's an example of some of the order it's generating:

<sortname>New Avengers: Illuminati, Vol. 2</sortname>
<sortname>New Avengers: Illuminati, Vol. 2</sortname>
<sortname>Nova</sortname>
<sortname>New X-Men</sortname>
<sortname>Nation X</sortname>
<sortname>Namor, The Sub-Mariner Annual</sortname>

As you can see, they are not in alphabetical order. Am I missing something? Any help is appreciated.

Was it helpful?

Solution

From quickly looking at your question, it looks like that you're using usort on an object of type SimpleXMLElement. However the function is intended to be used for an array.

Probably converting the object (or more precisely the iterator it offers) to an array first should solve your issue.

Explanation: In the example you've linked, the xpath function is used which already returns an array, here in your example that is not the case.

A function to turn the offered iterator to an array is iterator_to_array:

$array = iterator_to_array($xQuery, false);

usort($array, "cmp");

foreach ($array as $comic) ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top