user2184072
user2184072

Reputation: 47

Select and delete random keys from multidimensional array

I have one problem with randomness. I have example array.

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

I want to choose random keys from array to other array with specified size. In this second array I want values from other groups.

For example i got

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

I want to choose randomly specified ammount of variables ($amount) from $example, but of course - always from other groups.

Example result:

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

What I tried so far?

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]
}
}

I don't know now, what to fix or to do next.

Thanks for help!

Upvotes: 2

Views: 57

Answers (1)

Kanti
Kanti

Reputation: 601

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

test 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
    )
)

Upvotes: 2

Related Questions