2016-01-24 56 views
0

這是我在堆棧溢出中提出的第一個問題。我有點新手。不能使用PHP將用戶分配到相同的組中

我試圖自動分配學生隨機和平等(或大多相等,如果分配了奇數)組。現在,我只是試圖產生小組作業。稍後,這些信息將被存儲在數據庫中(還沒有),老師將能夠修改組的數量。

我可以讓學生分配到不同的隨機組,但它不會平分。我覺得這個問題是:

while ($rand_num == $value && $group_count[$rand_num] >= $group_size) 

它似乎並不像它做的比較或者是忽略了& &後的一切。

<?php 
$group_array = array("Abby" => 0 , "Billy" => 0 , "Cathy" => 0 , "Dillan" => 0, "Elizabeth" => 0 , "Fred" => 0 , "Geofery" => 0 , "Hank" => 0, "Ingrid" => 0 , "Jacob" => 0 , "Kylie" => 0 , "Lenord" => 0); 

$class_size = count($group_array); 
$num_groups = 3; 
$group_size = $class_size/$num_groups; 
$group_count = (array_count_values($group_array)); 

foreach ($group_array as $key => &$value) { 
    $rand_num = rand(1 , $num_groups);  
    while ($rand_num == $value && $group_count[$rand_num] >= $group_size) { 
     $rand_num = rand(1 , $num_groups); 
    }; 
    $value = $rand_num; 
    $group_count = (array_count_values($group_array)); 
}; 
//Group Assignments 
var_dump($group_array); 
//Users in each group 
var_dump($group_count); 
?> 

我在做什麼錯?

+0

所以你喜歡他們在同一時間同樣隨機劃分,對不對? –

+0

您可以對用戶數組使用shuffle,然後選擇第一個放入第一組,然後再次重新排列數組,並將第一個放入第二組,繼續,直到數組爲空。 – Perrykipkerrie

回答

1

我建議你更簡單,更清潔的方法。

爲4組實施例:

  1. 洗牌學生以隨機順序
  2. 分配組0,1,2,3,0,1,2,3,0,1,2,3等。

您可以實現這樣的:

<?php 
$n_groups = 4; 
$students = array("Abby", "Billy", "Cathy", "Dillan", "Elizabeth", "Fred", 
    "Geofery", "Hank", "Ingrid", "Jacob", "Kylie", "Lenord"); 

shuffle($students); // put students in random order 
$groups = []; // init empty groups 
foreach($students as $position => $student) { 
    $groups[$student] = $position % $n_groups; // put student into group based on his position (first student gets 0, then 1, 2, 3, then 0 again etc.) 
} 
print_r($groups); 
+0

謝謝!像魅力一樣工作。我很新,非常感謝。 –

0

爲什麼你的$group_array有作爲學生的名字鑰匙?任何purpouse?

我想出了這一點:

$students_array = ['Abby', 'Billy', 'Cathy', 'Dillan', 'Elizabeth', 'Fred', 'Geofery', 'Hank', 'Ingrid', 'Jacob', 'Kylie', 'Lenord', 'Katy']; 
shuffle($students_array); 

$class_groups = 3; 
$groups = []; 

foreach ($students_array as $key => $student) { 

    $assigned_group = $key % $class_groups; 
    $groups[$assigned_group][] = $student;  
} 

print_r($groups); 

我已經更具可讀性的瓦爾。並將學生小組放入一個數組中。

如果你得到奇數的學生,你最終會得到一個擁有+1學生的團體。

我認爲你的問題是試圖將學生隨機分配到組中,將它們按順序分配到組中將確保組具有相同數量的學生。

至於$key % $class_groups的值,它使用的是'模數'php的算術運算符。

計算機語言中的「mod」操作符就是其餘部分。對於 例如,

17模3 = 2

因爲

17/3 = 5 REM 2

這反過來又意味着

17 = 3 * 5 + 2

使用負數時有一些棘手的問題,但通常不需要使用 。

在數學(數論)中,這個術語有些不同。 「模數」實際上不是餘數,而是你用 除的數字;和「mod」不是一個操作符,而是一個標籤,告訴「在 兩個數量被認爲是一致的或相等的。對於 比如,我們會說

17 = 11(MOD 3)

(讀作 「17全等11,模3」),這意味着17和11 都離開同餘數時,如果你只是閱讀編程,你可能不會看到這個用法,但如果你深入瞭解它背後的數學,那麼值得注意的是 。

你可以閱讀從here.

+0

也工作,非常感謝你有關mod的附加信息。 –

相關問題