I am sorting & grouping publication data from an XML file. The methods I am currently using are working fine for the most part, although I feel like there is a more efficient way to do what I am trying to accomplish.
Here is a sample of what the target nodes look like:
<comic>
<id>117</id>
<mainsection>
<series>
<displayname>My Amazing Adventure</displayname>
<sortname>My Amazing Adventure</sortname>
</series>
</mainsection>
<issuenr>2</issuenr>
<seriefirstletter>
<displayname>M</displayname>
<sortname>M</sortname>
</seriefirstletter>
</comic>
Here are the current steps I am taking.
- Loading the XML file with SimpleXML
- Specifying the target node and using iterator_to_array to convert it to an array
- Using a usort function that compares (strcmp) the seriesname attribute, to sort all of the series alphabetically.
- I'm using a query string for each page to specify each letter of the alphabet and using an IF statement that compares the query string letter to the seriesfirstletter value. So only the applicable nodes are returned.
- I then begin my foreach statement. Echoing out the data I want, into LI items.
- Finally, I'm using jQuery to look at the ID's for each LI item and visually group them. I've created a PHP variable that uses the seriesname, with the spaces removed, for the ID's. It inserts a H4 heading with the proper series name, above the group and inserts a separating DIV below the group.
While the alphabetical sorting is working properly. I'm also wanting the issues within the same series to be sorted numerically. This is not currently working. Right now, the numeric sort order looks something like this: 1, 10, 12, 2, 3.
I would like to get the numerical sorting issue straightened out. I also feel like the grouping that I'm currently doing in jQuery, could be done in PHP, while I'm going through the loop. Any advice on a better / more efficient way to handle this data, would be greatly appreciated.
Let's say you've got all
<comic>
elements as an iterator already. First of all convert it to an array so we can use the array functions:Then you want to sort this array based on some value, here the value of the
<issuenr>
child. This can be done withusort
and the help of a callback function:The callback function just picks the concrete values you want to compare with each other and passes it along to
strnatcmp
which is the natural order comparison I commented above.The following code-example shows how to list all series that match a specific search letter,
natsort
ed and distinct (no duplicate names, grouped).The search and the grouping is both done with an
xpath
query:This will then output the sorted list:
In the next step you want to list all comics in that series, that would be an inner foreach:
Which will then fetch the comics for each series, output:
The code of the
xpath_string
function can be found in another answer of mine.You can use
Output
XML USed
__xsort Function Used