2017-03-08 79 views
2

我試圖做一個有趣的小PHP腳本,我有點卡住了。
我想劃分一個整數(例如5)在多個值。
例如:如何在PHP中將整數分成多個值?

$total = 5; 
$mike = 0; 
$ralf = 0; 
$ashley = 0; 

// Run the magic here 

echo "Mike has " . $mike . " apples, Ralf has " . $ralf ." apples and Ashley has " . $ashley . " apples"; 

,我希望會是這個樣子的輸出:
Mike has 2 apples, Ralf has 1 apples and Ashley has 2 apples

有沒有辦法如何做到這一點? :)
我不能這樣做硬編碼,因爲我想要的值是隨機的。

乾杯

+1

是這樣的:http://stackoverflow.com/questions/7289136/how-to-make-5-random-numbers-with-sum-of-100 – ashanrupasinghe

+0

的可能的複製[如何使5隨機數與總和100](http://stackoverflow.com/questions/7289136/how-to-make-5-random-numbers-with-sum-of-100) –

+0

你想要隨機整除整數,每個人都假設到目前爲止,或儘可能平等? –

回答

1

做這樣的:

$total = 5; 
$mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1) 
$ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf 
$ashley = $total - $mike - $ralf; // i hope you understand. 


// use it. 
+0

'Mike有3個蘋果,Ralf有3個蘋果,而Ashley有-1個蘋果':D,https://3v4l.org/Sf5EX – hassan

+0

@HassanAhmed oops是:P – mehulmpt

+0

你的更新:Mike有3個蘋果,Ralf有2個蘋果和阿什利有0個蘋果:D – hassan

1

像這樣的工作:

$people = array('mike','ralf','ashley'); 
$num = count($people); 
$sum = 5; // TOTAL SUM TO DIVIDE 
$groups = array(); 
$group = 0;  

    while(array_sum($groups) != $sum) { 

     $groups[$group] = mt_rand(0, $sum/mt_rand(1,5)); 

     if(++$group == $num){ 
      $group = 0; 
     } 
    } 

    // COMBINE ARRAY KEYS WITH VALUES 
    $total = array_combine($people, $groups); 

echo "Mike has " . $total['mike'] . " apples, Ralf has " . $total['ralf'] ." apples and Ashley has " . $total['ashley'] . " apples";  

的解決方案是從這個答案的啓發:https://stackoverflow.com/a/7289357/1363190

+0

我更喜歡Mehul Mohan的回答,但是由於這對於你想添加更多的人有幫助,所以我給了它一個+ 1 :) –

+0

謝謝,很高興它爲你解決。 –

0

希望這個功能做你的工作 。它也可以爲可變的人員工作。

divide_items(10,['mike','ralf','ashley']); 
function divide_items($total=1,array $persons){ 
    $progressed = 0; 
    for($i=0;$i<count($persons);$i++){ 
     echo $random_count = rand(1,$total); 
     if(($i==(count($persons)-1)) && $progressed<$total){ 
      $random_count1 =$total - $progressed; 
      echo $persons[$i]." has ".$random_count1 ." Items<br>"; 
      continue; 
     } 
     $progressed = $progressed+$random_count; 

     if($progressed<=$total){ 
      echo $persons[$i]." has ".$random_count ." Items<br>"; 
     }else{ 
      echo $persons[$i]." has 0 Item<br>"; 
     } 
     $total = $total-$random_count; 
     $progressed = 0; 

    } 
}