etrader Posted January 21, 2011 Share Posted January 21, 2011 I get strings via simplexml with this code $xml = simplexml_load_file("test.xml"); foreach ($xml->title->case as $value){ $param1 = $value->param1; $param2 = $value->param2; Now I want to randomize the xml items (not in their original order); but I cannot use shuffle($value); because it does not consider $value as an array. How can I make a random order? Quote Link to comment https://forums.phpfreaks.com/topic/225169-using-shuffle-with-simplexml/ Share on other sites More sharing options...
PFMaBiSmAd Posted January 21, 2011 Share Posted January 21, 2011 I would use SimpleXMLElement::count to get a count of the number of child elements, then use rand() to get a random number from zero to the count -1, then use that random number to access the corresponding child element. If you want to access more than one element randomly, you would make an array of the numbers, zero to count -1, shuffle that array, and then use that array of randomized numbers to access the corresponding child elements. Quote Link to comment https://forums.phpfreaks.com/topic/225169-using-shuffle-with-simplexml/#findComment-1162914 Share on other sites More sharing options...
etrader Posted January 21, 2011 Author Share Posted January 21, 2011 Sorry, I got a little bit confused. Could you please provide an example code doing this? Quote Link to comment https://forums.phpfreaks.com/topic/225169-using-shuffle-with-simplexml/#findComment-1162925 Share on other sites More sharing options...
salathe Posted January 21, 2011 Share Posted January 21, 2011 Get an array of the <case> elements by using XPath like $cases = $xml->xpath('title/case'); or manually create an array of <case> elements $cases = array(); foreach ($xml->title->case as $case) { $cases[] = $case; } then shuffle to your heart's content. Quote Link to comment https://forums.phpfreaks.com/topic/225169-using-shuffle-with-simplexml/#findComment-1162928 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.