note 26583 modified in function.array-push by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 14:48:27 +0000 |
| Subject: | note 26583 modified in function.array-push by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80000@lists.php.net to get a copy of this message | ||
Another associative array sorter. Will handle null arrays, and should correctly handle
multidimensionals. Essentially, it pulls all the keys into an array, randomizes that array, then
spits out a reconstructed array based on the randomized keys.
I would have used array_keys() instead of the first foreach(), but unfortunately the array returned
gets spit back in hash order, not array order. My particular needs required me to have reproducable
randomizations based on specific mt_srand() values. For most people who just need a random array
output with no reproduction, you can substitute the line beneath.
<?php
function assocArrayShuffle($inarray) {
if(!$inarray) return $inarray;
$keys = array(); $rkeys = array();
foreach($inarray as $k => $v) $keys[] = $k;
// OR... $keys = array_keys();
while(count($keys)>0) {
list($k) = array_splice($keys, mt_rand(0, count($keys)-1), 1);
$rkeys[] = $k;
}
foreach($rkeys as $k => $v) $outarray[$v] = $inarray[$v];
return $outarray;
}
?>
--was--
Another associative array sorter. Will handle null arrays, and should correctly handle
multidimensionals. Essentially, it pulls all the keys into an array, randomizes that array, then
spits out a reconstructed array based on the randomized keys.
I would have used array_keys() instead of the first foreach(), but unfortunately the array returned
gets spit back in hash order, not array order. My particular needs required me to have reproducable
randomizations based on specific mt_srand() values. For most people who just need a random array
output with no reproduction, you can substitute the line beneath.
function assocArrayShuffle($inarray) {
if(!$inarray) return $inarray;
$keys = array(); $rkeys = array();
foreach($inarray as $k => $v) $keys[] = $k;
// OR... $keys = array_keys();
while(count($keys)>0) {
list($k) = array_splice($keys, mt_rand(0, count($keys)-1), 1);
$rkeys[] = $k;
}
foreach($rkeys as $k => $v) $outarray[$v] = $inarray[$v];
return $outarray;
}
http://php.net/manual/en/function.array-push.php