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.
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: