从多维数组中选择并删除随机密钥

时间:2015-10-13 13:41:55

标签: php arrays random

我有一个随机问题。 我有示例数组。

$example=array(
    'F1' => array('test','test1','test2','test5'),
    'F2' => array('test3', 'test4'),
    'F3' => array('one','twoo','threee','x'),
    'F5' => array('wow')
)

我想从数组中选择随机键到指定大小的其他数组。在第二个数组中,我想要来自其他组的值。

例如我得到了

  $amounts = array(4,3,1,2,1);

我想从$ example中选择随机指定的ammount变量($ amount),但当然 - 总是来自其他组。

示例结果:

   $result=(
array(4) => ('test','test4','x','wow'),
array(3) => ('test2','test3','three'),
array(1) => ('test1')
array(2) => ('test5','one')
array(1) => ('twoo')

到目前为止我尝试了什么?

foreach($amounts as $key=>$amount){
   $random_key[$key]=array_rand($example,$amount);
   foreach($result[$key] as $key2=>$end){
    $todelete=array_rand($example[$end]);
    $result[$key][$key2]=$example[$amount][$todelete]
}
}

我现在不知道,接下来要做什么或做什么。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

$example = array(
    'F1' => array('test', 'test1', 'test2', 'test5'),
    'F2' => array('test3', 'test4'),
    'F3' => array('one', 'twoo', 'threee', 'x'),
    'F5' => array('wow')
);
$amounts = array(4, 3, 1, 2, 1);

$result = array();

$example = array_values($example);
//randomize the array
shuffle($example);
foreach ($example as $group) {
    shuffle($group);
}

//sort the example array by child length
usort($example, function ($a, $b) {
    return count($b) - count($a);
});

foreach ($amounts as $amount) {
    $tmpResult = array();
    for ($i = 0; $i < $amount; $i++) {
        if(empty($example[$i])){
            throw new \InvalidArgumentException('The total number of values in the array exceed the amount inputed');
        }
        $tmpResult[] = array_pop($example[$i]);
    }

    $result[] = $tmpResult;

    //sort the example array again by child length
    usort($example, function ($a, $b) {
        return count($b) - count($a);
    });
}

print_r($result);

测试结果:

Array
(
    [0] => Array
    (
        [0] => test5
        [1] => x
        [2] => test4
        [3] => wow
    )
    [1] => Array
    (
        [0] => test2
        [1] => threee
        [2] => test3
    )
    [2] => Array
    (
        [0] => test1
    )
    [3] => Array
    (
        [0] => twoo
        [1] => test
    )
    [4] => Array
    (
        [0] => one
    )
)