tags:

views:

153

answers:

4
A: 

Artefacto-

the last 2 code blocks show the function for sorting the nodes by name (the location nodes).


// start the sortCities
function sortCities($a, $b){
    return strcmp($a->location, $b->location);
}
// start the sortStates
function sortStates($t1, $t2) {
    return strcmp($t1['statename'], $t2['statename']);
}

the second function does sort by attribute (statename) in the array but, combing the two function or rather nesting them so that the states and the cities get sorted alphabetically has got me stumped.

+1  A: 

My approach was to convert the SimpleXMLElement objects into arrays:

$doc = new SimpleXMLElement($xml);
$states =  get_object_vars($doc->prop->children());
$states = $states["state"];
usort($states, function($t1, $t2) { return strcmp($t1['statename'], $t2['statename']); });
array_walk($states,
    function (&$state) {
        $state = get_object_vars($state);
        array_walk($state["info"],
            function (&$el) {
                $el = get_object_vars($el);
            }
        );
        usort($state["info"],
            function($a, $b) { return strcmp($a["location"], $b["location"]); }
        );
    }
);
Artefacto
A: 

@Artefacto,

Thanks for the reply. Seems to make sense the way it's nested. Issue is, none of my servers run PHP 5.3. So the generic functions are tossing errors. I should have mentioned this but didn't think about it. They are running 5.2. I have been trying to revert the script back and have gotten stuck with a section.

<?php
$doc = simplexml_load_file('test.xml');
$states =  get_object_vars($doc->prop->children());
$states = $states["state"];
function sortStates($t1, $t2) { 
    return strcmp($t1['statename'], $t2['statename']); 
};
usort($states, "sortStates");

/* this is just here for testing */
echo '<pre>';
print_r($states);
echo '</pre>';
/* end testing */

/*
array_walk($states,
    function (&$state) {
        $state = get_object_vars($state);
        array_walk($state["info"],
            function (&$el) {
                $el = get_object_vars($el);
            }
        );
        usort($state["info"],
            function($a, $b) { return strcmp($a["location"], $b["location"]); }
        );
    }
);
*/
?>

The commented out section starting with the array_walk. I can't figure out how to rewrite the 'function (&$state)' with out the next line dying.

A: 

changing this

foreach ($prop->children() as $stateattr)

to this

foreach ($sortedStates as $stateattr)

did it.

could have sworn I tried that already.