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

Link to comment
Share on other sites

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

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.