dou*_*man 2 php arrays dynamic associative explode
我试图生成一个随机值的关联数组.例如,如果我给你这个字符串:
something, anotherThing, foo, bar, baz
Run Code Online (Sandbox Code Playgroud)
(字符串的长度是动态的 - 所以可能有10个项目,或15个);
我想基于这些值创建一个数组:
$random = rand();
array("something"=>$random, "anotherThing"=>$random, "foo"=>$random, "bar"=>$random, "baz"=>$random);
Run Code Online (Sandbox Code Playgroud)
它根据给定的值来构建数组.
我知道如何将它们排序成这样的数组:
explode(", ", $valueString);
Run Code Online (Sandbox Code Playgroud)
但是如何分配值以使其成为关联数组?
谢谢.
注意:我假设您希望每个项目具有不同的随机值(这与您的示例中不完全相同).
使用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);
Run Code Online (Sandbox Code Playgroud)
对于早期版本,或者如果您不想使用array_map,您可以在更实际的情况下执行相同的操作,但稍微更冗长的方式:
$keys = array('something', 'anotherThing', 'foo', 'bar', 'baz');
$result = array();
foreach($keys as $key) {
$result[$key] = mt_rand();
}
print_r($result);
Run Code Online (Sandbox Code Playgroud)