<?php $num = 5; $total = 20; function randArray($num,$total){     $array = array();     $array = array_pad($array,$num,0);     for($i=0;;$i++){         for($j=0;$j<$num;$j++){         $rand = rand(0,1);         if( (array_sum($array) + $rand) >= $total ){ $array[$j] += $total - array_sum($array); return $array; }else{ $array[$j] += $rand; } } } } $array = randArray($num,$total); echo '<pre class="brush:php;toolbar:false">'; print_r($array); echo '<br />'; echo array_sum($array); echo '<br />'; $key = array_rand($array); echo $key; echo '<br />'; echo $array[$key];
The above introduces how PHP randomly allocates a specified number to an array of specified books, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.