note 63748 rejected from function.array-rand by bjori
| From: | bjori@php.net | Date: | Thu, 30 Mar 2006 10:15:50 +0000 |
| Subject: | note 63748 rejected from function.array-rand by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-107010@lists.php.net to get a copy of this message | ||
Note Submitter: almond at acm dot org
----
If you use array_rand() with a labeled array of object, it appears to generate an array of numeric
indexes and not an array of string indexes (at least under PHP 4.4.2). For example, if you have
<?php
$data = array ('name1' => $obj1, 'name2' => $obj2, ...);
?>
Then <?php array_rand(data,2) ?> will produce something like
ARRAY([0] => 13, [1] =>5) and not ARRAY([0] => 'name13', [1] =>
'name5').
Given this behavior, I produced the following code to produce a random sample (without replacement)
from a labeled array preserving the labels.
<?php
function sample($data,$n) {
$result = array();
$keys = array_keys($data);
$members = array_rand($keys,$n);
foreach ($members as $index) {
$key = $keys[$index];
$result[$key] = $data[$key];
}
return $result;
}
?>