Jump to content

Using shuffle() with Simplexml


etrader

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/225169-using-shuffle-with-simplexml/
Share on other sites

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.

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. :)

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.