Beginner programmer here.
I am in php, working with a dom document nodelist comprising of selected nodes retrieved from an XPath query on an xml file. Excerpt of contents of nodelist:
<properties>
<property>
<price>270</price>
<address>3/2 Farran Street, Castlemaine, VIC, Australia</address>
<infants>3</infants>
</property>
<property>
<price>250</price>
<address>2/37 William Street, Castlemaine, VIC, Australia</address>
<infants>2</infants>
</property>
<property>
<price>250</price>
<address>2/37 William Street, Castlemaine, VIC, Australia</address>
<infants>3</infants>
</property>
...
I wish to sort the nodelist by price
ascending, and in the case of matching prices, by no of infants
descending. In the above snippet, for example, the result would be:
<property>
<price>250</price>
<address>2/37 William Street, Castlemaine, VIC, Australia</address>
<infants>3</infants>
</property>
<property>
<price>250</price>
<address>2/37 William Street, Castlemaine, VIC, Australia</address>
<infants>2</infants>
</property>
<property>
<price>270</price>
<address>3/2 Farran Street, Castlemaine, VIC, Australia</address>
<infants>3</infants>
</property>
I have seen some sorting questions answered relating to multi-dimensional arrays but I can't seem to translate these to nodelists. I can sort by price
ok (see below), but I can't determine how to then sort by infants
.
$properties = iterator_to_array($matches); // where matches = a return from an XPath query
usort($properties, 'sortByPrice');
function sortByPrice ($a, $b) {
$aPrice = $a->getElementsByTagName("price");
$aPrice = $aPrice->item(0)->nodeValue;
$bPrice = $b->getElementsByTagName("price");
$bPrice = $bPrice->item(0)->nodeValue;
return (int) $aPrice - (int) $bPrice;
}