Xml Sorting Problem

Hi, I am loading an XML with DOMDocument. The XML has prices which come like: <![CDATA[ €380,000 ]]> for Euros and like: <![CDATA[ $3,000 ]]> for Dollars.

I am inserting the nodeValues into and array to use with CListView widget. The problem is that when I sort by price the sorting is not correct. I believe the problem is that sorting is done on a string basis and not on a numeric basis because it makes $3,000 > $10,000.

Any idea on how to solve this?

Thanks in advance!

German

Where and how do you sort? Chances are indeed that those cdata fragments are sorted as strings and hence in lexicographic order.

Hi, thanks for your reply.

I sort with the CListView widget. I use a CArrayDataProvider.

I agree with you, the thing is I can’t find a way to transform '€’380,000 into a number. Any ideas?

Actually I the price in the XML comes like this: & # 8 3 6 4 ; 380,000 (all together) for Euros and & # 3 6 ; 295,000 (all together)for Dollars

You would need to find a way to strip the currency entity and the number formatting. Is there any reason why they are already in the source XML?

I guess you could try something like this, assuming that the currency always uses the same character to represent the decimal point:




// Remove any character that is not numeric or a decimal point

$stripped = preg_replace('/[^0-9.]/', '', $original);



If you want to handle the whole array, $original can be replaced with an array of values and $stripped will be returned as an array.

EDIT:

I suggest you build up an additional column in your array (to hold the numeric values) and use one of the usort functions to perform a custom sort. You may need to cast the values in this column to doubles in order to assure numeric sorting, so don’t use the values for anything other than the sort.

To both of you, thank you very much!!! I was thinking the solution might have been something of this type. It’s good to share doubts, hopes it helps someone else!

XML is a linear data structure, so sorting is not easy to do directly. But if you convert it into array, then it’s much easier to sort. Of course, you have to convert it back to XML after sorting.

Most people will like to use simpleXML to convert XML to array, and here is some links to convert array into XML: