Reputation: 1
I'm trying to split tasks for two persons randomly by generating random number for every task from 1 to 2.
the problem is that I have duplicate tasks. how to generate the same number for duplicates without having to delete them ? example :
<?php
$tasks = array('task1','task4','task2','task3','task4','task3','task4','task5');
foreach($tasks as $task)
{
$rand = rand(1,2);
$array = array('task' => $task,'rand'=> $rand);
echo $array['task']."==>";
echo $array['rand']."<br>";
}
?>
Upvotes: 0
Views: 89
Reputation: 4157
You could us array_fill_keys()
to create an array with all the tasks as keys, then use array_walk()
to assign random numbers to all the keys.
$tasks = array('task1','task4','task2','task3','task4','task3','task4','task5');
//use the tasks as keys for a new array. Duplicates will be filtered out.
$task_rand = array_fill_keys( $tasks, false );
//then "walk" the new array, assigning a randum number to each task
array_walk($task_rand, function(&$value){$value= rand(1,2);});
//sort the array, so task1 comes before task2 etc
ksort($task_rand);
The result of `$task_rand`:
Array
(
[task1] => 2
[task2] => 1
[task3] => 2
[task4] => 1
[task5] => 1
)
Upvotes: 0
Reputation: 563
$tasks = array('task1', 'task4', 'task2', 'task3', 'task4', 'task3', 'task4', 'task5');
$output = [];
foreach ($tasks as $task) {
if (!isset($output[$task])) {
$output[$task] = rand(1, 2);
}
}
Result: var_dump($output);
array (size=5)
'task1' => int 2
'task4' => int 2
'task2' => int 2
'task3' => int 1
'task5' => int 1
Get the number for a certain task:
var_dump($output['task3']);
int 1
This is easy to use, but the duplicates will be deleted. As you said, you don't like that. (But it would be easier)
There you need a new array, with task and the number.
$tasks = array('task1', 'task4', 'task2', 'task3', 'task4', 'task3', 'task4', 'task5');
$numbers = []; // saving the random number, so the same task will get the same number
$result = [];
foreach ($tasks as $task) {
if (isset($result[$task])) {
$number = $numbers[$task];
} else {
$number = rand(1, 2);
$numbers[$task] = $number;
}
$result[] = [
'task' => $task,
'number' => $number,
];
// or $result[] = $number;
// then only the number is saved at the position of $task
}
result var_dump($result);
array (size=8)
0 =>
array (size=2)
'task' => string 'task1' (length=5)
'number' => int 2
1 =>
array (size=2)
'task' => string 'task4' (length=5)
'number' => int 1
2 =>
array (size=2)
'task' => string 'task2' (length=5)
'number' => int 2
3 =>
array (size=2)
'task' => string 'task3' (length=5)
'number' => int 2
4 =>
array (size=2)
'task' => string 'task4' (length=5)
'number' => int 1
5 =>
array (size=2)
'task' => string 'task3' (length=5)
'number' => int 2
6 =>
array (size=2)
'task' => string 'task4' (length=5)
'number' => int 1
7 =>
array (size=2)
'task' => string 'task5' (length=5)
'number' => int 1
Upvotes: 2