随机数组键和值php

时间:2017-11-15 11:06:33

标签: php arrays

我想随机改组php数组的键和值。我已经找到了改变顺序的解决方案,但是我想要改变键和价值观。

数组array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour')例如会变为array('oui' => 'yes, 'no' => 'non', 'bonjour' => 'hello')。请注意,第一个和最后一个值具有随机交换的键和值。

我知道您可以使用array_flip来翻转数组中的键和值。但这会翻转所有键和值,而我想随机翻转几个键和值。我该怎么做?

2 个答案:

答案 0 :(得分:1)

$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');

foreach($array as $key => $value) {
    if (0 === rand(0,1)) {
        $array[$value] = $key;
        unset($array[$key]);
    }
}

答案 1 :(得分:1)

$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');

// Run it in a foreach loop
foreach ($array as $key => $val){
    // rand(0, 1) will return either 0 or 1
    // It's up to you which value you want to set as anchor.
    if (rand(0, 1) === 0){
        // Set the value as key,
        // then set the key as value.
        $array[$val] = $key;

        // Delete the original one.
        unset($array[$key]);
    }
}