We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

random() method in php

Medium Priority
404 Views
Last Modified: 2012-05-05
hello!

i have a function in php that randomly pairs my set of instructors to my set of subjects.the number of subjects is greater than the number of instructors. how can i fairly/evenly assign subjects to instructors such that no instructor gets too many subjects??

can anyone show me a code in php using the random method that solves this problem?

thanks!
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2006
Commented:
You can also just shuffle the students array, and then assign them in a loop to the instrructors:


<?php

  $students = array('a','b','c','d','e','f','g','h','i','j','k');
  $instructors = array('I','II','III','IV','V');
 
  $assigned = array();
 
  $cInstructors = count($instructors);
  $cStudents    = count($students);
 
  shuffle($students);
 
  for($i = 0; $i < $cStudents; $i++) {
    $cIns = $i % $cInstructors;
    if(!isset($assigned[$cIns])) $assigned[$cIns] = array();
    $assigned[$cIns][] = $students[$i];
  }
 
  echo '<pre>';
  print_r($assigned);
  echo '</pre>';
 
?>

The $assigned array, will hold $instructorId => array($student, $student, $student) key-value pairs.

-r-

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2006

Commented:
Sorry, the forloop didn't retrieve the actual instructor Id. Use this instead:

<?php

  $students = array('a','b','c','d','e','f','g','h','i','j','k');
  $instructors = array('I','II','III','IV','V');
 
  $assigned = array();
 
  $cInstructors = count($instructors);
  $cStudents    = count($students);
 
  shuffle($students);
 
  for($i = 0; $i < $cStudents; $i++) {
    $kIns = $instructors[$i % $cInstructors];
    if(!isset($assigned[$kIns])) $assigned[$kIns] = array();
    $assigned[$kIns][] = $students[$i];
  }
 
  echo '<pre>';
  print_r($assigned);
  echo '</pre>';
 
?>
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.