note 93214 added to function.shuffle
| From: | Anonymous at osu1 dot php dot net | Date: | Fri, 28 Aug 2009 16:18:52 +0000 |
| Subject: | note 93214 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159992@lists.php.net to get a copy of this message | ||
I needed a simple function two shuffle a two dimensional array. Please note the second level arrays
must be indexed using integers, for example $myarray[0]["Name"] and not
$myarray["One"]["Name"]. Here is the function:
<?php
function twodshuffle($array)
{
// Get array length
$count = count($array);
// Create a range of indicies
$indi = range(0,$count-1);
// Randomize indicies array
shuffle($indi);
// Initialize new array
$newarray = array($count);
// Holds current index
$i = 0;
// Shuffle multidimensional array
foreach ($indi as $index)
{
$newarray[$i] = $array[$index];
$i++;
}
return $newarray;
}
?>
Please note it only works on two dimensional arrays. Here is an example:
<?php
$myarray = array("Google" => array("Name" => "Google",
"URL" => "www.google.com", "Usage" => "Googling"),
"Yahoo" => array("Name" => "Yahoo", "URL" =>
"www.yahoo.com", "Usage" => "Yahooing?"), "Ask" =>
array("Name" => "Ask", "URL" => "www.ask.com",
"Usage" => "Asking Jeeves"));
print_r(twodshuffle($myarray));
/* And the result is:
Array ( [0] => Array ( [Name] => Ask [URL] => www.ask.com [Usage] => Asking Jeeves ) [1]
=> Array ( [Name] => Google [URL] => www.google.com [Usage] => Googling ) [2] =>
Array ( [Name] => Yahoo [URL] => www.yahoo.com [Usage] => Yahooing? ) )
*/
?>
Hope you find it useful!
----
Server IP: 208.69.120.35
Probable Submitter: 69.142.233.248
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- https://master.php.net/note/edit/93214
Del: integrated -- https://master.php.net/note/delete/93214/integrated
Del: useless -- https://master.php.net/note/delete/93214/useless
Del: bad code -- https://master.php.net/note/delete/93214/bad+code
Del: spam -- https://master.php.net/note/delete/93214/spam
Del: non-english -- https://master.php.net/note/delete/93214/non-english
Del: in docs -- https://master.php.net/note/delete/93214/in+docs
Del: other reasons-- https://master.php.net/note/delete/93214
Reject -- https://master.php.net/note/reject/93214
Search -- https://master.php.net/manage/user-notes.php