note 63748 added to function.array-rand
| From: | almond at acm dot org | Date: | Wed, 29 Mar 2006 22:02:44 +0000 |
| Subject: | note 63748 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-106978@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 144.81.32.1
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- http://master.php.net/note/edit/63748
Del: integrated -- http://master.php.net/note/delete/63748/integrated
Del: useless -- http://master.php.net/note/delete/63748/useless
Del: bad code -- http://master.php.net/note/delete/63748/bad+code
Del: spam -- http://master.php.net/note/delete/63748/spam
Del: non-english -- http://master.php.net/note/delete/63748/non-english
Del: in docs -- http://master.php.net/note/delete/63748/in+docs
Del: other reasons-- http://master.php.net/note/delete/63748
Reject -- http://master.php.net/note/reject/63748
Search -- http://master.php.net/manage/user-notes.php