I want to create a sortable list that looks something like
The data comes from multiple same structured xml files:
$xmlfile="
<Level1>
<Level2>
<Level2Item VAR1="1" VAR2="2" ... />
<Level2Item VAR1="4" VAR2="5" ... />
<Level2Item VAR1="7" VAR2="8" ... />
</Level2>
</Level1>";
//Extract each item
$xml = new SimpleXMLElement($xmlfile);
foreach ($xml->Level2[0] as $result) {
array_push($VAR1Array, $result['VAR1']);
array_push($VAR2Array, $result['VAR2']);
//... etc etc
}
//sort
//$sortedArray = sort($VAR1Array);
Output
Array(
[0] => SimpleXMLElement Object([0] => 1)
[1] => SimpleXMLElement Object([0] => 4)
[2] => SimpleXMLElement Object([0] => 7)
)
From this XML structure, what's the best way of storing the data in one array? I want to be able to gather all the data in one array so I can sort it by one or 2 VARs and display the results.
I'm not quite sure what kind of sorting you're trying to do (you should specify with some examples). But optimally, you wouldn't be loading XML fragments into your array.
$xmlfile="
<Level1>
<Level2>
<Level2Item VAR1="1" VAR2="2" ... />
<Level2Item VAR1="4" VAR2="5" ... />
<Level2Item VAR1="7" VAR2="8" ... />
</Level2>
</Level1>";
//Extract each item
$xml = new SimpleXMLElement($xmlfile);
foreach ($xml->Level2[0] as $result) {
$VAR1Array[] = (int) $result['VAR1'];
$VAR2Array[] = (int) $result['VAR2'];
//... etc etc
}
Last, sort() works by reference, so don't equate it to a variable (i.e. just say sort($array); as the entire line, and then $array will be sorted. If you cast as ints like I do in the above example you can use php's default sort function without using a user-defined comparison function like others suggested. And array_push is a little bit slower and harder to read than using php's $var[] syntax to add a new element to an array.
Also, I'm fully sure that you can't assign $xmlfile that way (making unescaped double quotes inside double quotes.
In this code, the best way to define $xmlfile would be:
$xmlfile = <<<XML
<Level1>
<Level2>
<Level2Item VAR1="1" VAR2="2" ... />
<Level2Item VAR1="4" VAR2="5" ... />
<Level2Item VAR1="7" VAR2="8" ... />
</Level2>
</Level1>
XML;
or
$xmlfile = '
<Level1>
<Level2>
<Level2Item VAR1="1" VAR2="2" ... />
<Level2Item VAR1="4" VAR2="5" ... />
<Level2Item VAR1="7" VAR2="8" ... />
</Level2>
</Level1>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With