window rain

Iain's nonsensical words

This is how I've tackeled the problem of changing the order of some SimpleXML objects.

Adding an attribute to the top level of an object can add as the position reference.
So Passing an array of SimpleXML objects to the following function will return the same array of objects, but reordered by the $key attribute.

[Edited 26th Feb 2008]
function xmlSort($dataArray, $sortKey)
{
$outputArray = array();

for ($i = 0; $i < count($dataArray); $i++)
{
$sortArray[] = (int)$dataArray[$i]{$sortKey};
}

for ($i = 0; $i < count($sortArray); $i++)
{
$outputArray[] = $dataArray[$sortArray[$i]];
}

for ($i = 0; $i < count($outputArray); $i++)
{
$outputArray[$i]{$sortKey} = $i;
}

return $outputArray;
}

See PHP.net SimpleXML for the dataset used.

Adding 'pos="#"' to each element will allow for reordering.

An example usage would be:
$sorted_xml = xmlSort($xml->movie, 'pos');


Diary feed
 + RSS 2.0 XML feed


Everything on this site is (c) Iain Cuthbertson unless otherwise noted.