Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为数组生成随机值_Php_Arrays - Fatal编程技术网

Php 为数组生成随机值

Php 为数组生成随机值,php,arrays,Php,Arrays,如何为数组生成随机值,如以下示例所示: 固定数组键 $array = array( "a"=>"", "b"=>"", "c"=>"", "d"=>"" ); 从字母表字符串生成值后 // string & length like key array $str = "abcd"; $array = array( "a"=>"c", "b"=>"d", "c"=>"a", "d"

如何为数组生成随机值,如以下示例所示:

固定数组键

$array = array(
    "a"=>"",
    "b"=>"",
    "c"=>"",
    "d"=>""
);
从字母表字符串生成值后

// string & length like key array 
$str = "abcd";

$array = array(
    "a"=>"c",
    "b"=>"d",
    "c"=>"a",
    "d"=>"b"
);
因此,键得到的值与值得到键的值相同

如何在php中构建它?
谢谢你可以这样做

创建一个值数组

$arr = array("a","b","c","d")
然后生成一个介于0和数组长度之间的随机数

$ran = rand(0,count($arr))
然后得到一个随机值

$value = $arr[$ran]

以下是正确的解决方案:

<?php

// Input array
$keys = ['a', 'b', 'c', 'd'];

if (empty($keys) || count($keys) % 2 > 0) {
    throw new Exception('Number of items must be even or array cannot be empty.');
}

$result = [];
for ($i = 0; $i <= count($keys) / 2; $i++) {
    $parent = array_splice($keys, array_rand($keys), 1)[0];
    $child = array_splice($keys, array_rand($keys), 1)[0];

    $result[$parent] = $child;
    $result[$child] = $parent;
}

var_dump($result);

看看排列的概念。另外,array_rand可能会有所帮助。到目前为止,您自己是否尝试过任何代码?