使用array_rand选择顶级数组及其所有后代

时间:2011-03-30 19:18:55

标签: php multidimensional-array

大家好,我对如何解决这个问题感到有些困惑。任何帮助将不胜感激。

我有以下代码。

$worms_level1 = $this->catch_the_worm_model->get_worms_by_level(1);
$captured_worms = array();

for ($i = 0; $i < $num_worms; $i++)
{
    $captured_worms[$i] = array_rand($worms_level1);
}

return $captured_worms;

$ worms_level1多维数组采用以下格式:

Array ( [0] => Array ( [worm_id] => 1 
                       [worm_name] => Verm 
                       [worm_description] => The most common verm, not a huge threat but a great nuisance. 
                       [worm_level] => 1 
                       [worm_value] => 1 ) 

        [1] => Array ( [worm_id] => 2 
                       [worm_name] => Vermichav 
                       [worm_description] => Vermichav loves a scuffle. He's been known to spit in Wormcatcher's eyes and inflict pain by cigarette burns. 
                       [worm_level] => 1 [worm_value] => 1 )
     )

在代码成功选择随机数组并将其保存到新数组时,例如

Array ( [0] => 1 [1] => 1 )

但我也希望将后代数组保存到新数组中。

1 个答案:

答案 0 :(得分:1)

怎么样:

$captured_worms=array();
$howmany=20;
do{
    $howmany-=count($captured_worms);//decreases $howmany by the number we already grabbed
    shuffle($multiarray); //reorder the multiarray randomly
    $captured_worms=array_slice($multiarray,0,$howmany);//get as many elements as you want
} while(count($captured_worms)<$howmany); //ensures at least $howmany