Hello,
I am attempting to parse an XML file to create a multidimensional array of unknown/unlimited depth. Shown below is the intended structure of the array:
$items = array(
['item1'] => array(
['name'] => 'name here',
['command'] => 'command here'
)
['item2'] => array( // name and command etc
)
['nest'] => array(
['name'] => 'nest name here';
['items'] => array(
['item'] = array(
['name'] => 'name here',
['command'] => 'command here'
))))
Essentially, I would like an array that consist of items, each item itself being an array that contains item-specific properties. On the same level as the items can be found nests. Nests are to contain an array of items (again, also arrays) but may also include further nests. This could hypothetically continue any number of times. The two files I am currently using are below.
##### TEST3.php #####
<?php
function subMenuRecursion($xml, $array = array(), $itemcount = 1, $nestcount = 1)
{
foreach($xml->children() as $k => $v)
{
if ((string) $k == 'item')
{
$array["item$itemcount"]['text'] = (string) $v;
$array["item$itemcount"]['command'] = (string) $v['command'];
$itemcount++;
}
}
foreach($xml->children() as $k => $v)
{
if ((string) $k == 'nest')
{
$array["nest$nestcount"] = array('name' => (string) $v['name'], 'items' => array());
$nestcount++;
subMenuRecursion($xml->nest, $array["nest".($nestcount-1)]['items']);
}
}
return $array;
}
$file = 'test3.xml';
$xmlobject = simplexml_load_file($file);
$a = subMenuRecursion($xmlobject->sub_menu);
echo '<pre>' . print_r($a, 1) . '</pre>';
?>
##### TEST3.XML #####
<blah>
<sub_menu>
<item command="DefaultCommand">Main (Not nested 1)</item>
<item command="DefaultCommand">Main 2 (Not nested 2)</item>
<nest name="Cont">
<item command="Contact">NESTED Contact 1</item>
<item command="Contact">NESTED Contact 2</item>
</nest>
</sub_menu>
</blah>
The problem is that the 'nested' items are not added to the array that is generated inside the current array ($array['nest1']['items']). My idea behind the function is that by creating a new array in the following line of code:
$array["nest$nestcount"] = array('name' => (string) $v['name'], 'items' => array());
and then by passing the recursive call this newly generated array, it should add the nested items to the multidimensional array. These items, however, are not being added and I am completely at a loss. I am running PHP 5.3 on a localhost using WAMP.
Any assistance would be extremely useful and much appreciated. Thank you.