简体   繁体   English

使用随机值PHP创建关联数组

[英]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); (字符串的长度是动态的 - 所以可能有10个项目,或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);

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: 使用PHP 5.3或更高版本,您可以最轻松地执行此操作:

$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: 对于早期版本,或者如果您不想使用array_map ,您可以在更实际的情况下执行相同的操作,但稍微更冗长的方式:

$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 所有的例子都很好,但并不简单

  1. Init array Init数组

     $arr = array(); 
  2. How many values your need? 你需要多少价值?

     $m = 10; 
  3. 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. 我想你有$ key_array中的键。 This will make $random the value of each key: 这将使每个键的值随机$ random:

$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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM