exxer Posted January 14, 2019 Share Posted January 14, 2019 Hello, Im trying to figure out how to create multidimensional array from xml file that looks like this: <root> <item> <name>name A</name> <category>category 1</name> <desc>desc A</desc> </item> <item> <name>name B</name> <category>category 1</name> <desc>desc B</desc> </item> <item> <name>name C</name> <category>category 2</name> <desc>desc C</desc> </item> </root> In the end i would like to get output that have items grouped under their categories, something like this: Category 1 name A desc A name B desc B Category 2 name C desc C I have a clue on how to pull the data out of array but I cant figure out how to actually make it :) Any help or directions would be great, thanks! Quote Link to comment Share on other sites More sharing options...
requinix Posted January 14, 2019 Share Posted January 14, 2019 You don't need a literal array. 1 Quote Link to comment Share on other sites More sharing options...
Barand Posted January 14, 2019 Share Posted January 14, 2019 If you want this Array ( [category 1] => Array ( [name A] => desc A [name B] => desc B ) [category 2] => Array ( [name C] => desc C ) ) Then $xml = simplexml_load_string($input); $cats = []; foreach ($xml->item as $itm) { if (!isset($cats[(string)$itm->category])) { $cats[(string)$itm->category] = []; } $cats[(string)$itm->category][(string)$itm->name] = (string)$itm->desc; } 1 Quote Link to comment Share on other sites More sharing options...
exxer Posted January 15, 2019 Author Share Posted January 15, 2019 So many thanks Barand, that is what I need. Your code combined with this foreach($cats as $cat=>$data){ echo "$cat <br />"; foreach($data as $name=>$desc){ echo "$name<br /> ($desc)<br />"; } } gave me output that I wanted. Again, many thanks. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.