Creating an associative array with random values PHP
I am trying to generate an associate array with random values. For example, if I give you this string:
something, anotherThing, foo, bar, baz
(the length of the string is dynamic - so there could be 10 items, or 15);
I would like to create an array based on those values:
$random = rand();
array("something"=>$random, "anotherThing"=>$random, "foo"=>$random, "bar"=>$random, "baz"=>$random);
开发者_JAVA技巧And it builds the array based on how many values it's given.
I know how to order them into an array like so:
explode(", ", $valueString);
But how can I assign the values to make it an associative array?
Thanks.
NOTE: I am assuming that you want each item to have a different random value (which is not exactly what happens in your example).
With PHP 5.3 or later, you can do this most easily like so:
$keys = array('something', 'anotherThing', 'foo', 'bar', 'baz');
$values = array_map(function() { return mt_rand(); }, $keys);
$result = array_combine($keys, $values);
print_r($result);
For earlier versions, or if you don't want to use array_map
, you can do the same thing in a more down to earth but slightly more verbose manner:
$keys = array('something', 'anotherThing', 'foo', 'bar', 'baz');
$result = array();
foreach($keys as $key) {
$result[$key] = mt_rand();
}
print_r($result);
all example are good, but not simple
Init array
$arr = array();
How many values your need?
$m = 10;
save random to all elements of array
for ($i=0;$i<$m;$i++) { $arr[$i] = mt_rand(); }
Why make more complex this simple example?
, Arsen
I suppose you have the keys in $key_array. This will make $random the value of each key:
$random = rand();
$array = array_fill_keys($key_array, $random);
If you need a way to apply different random values to each element, here's one (of several) solutions:
$array = array_fill_keys($key_array, 0);
foreach($array as &$a) {
$a = rand();
}
精彩评论