无法使用List()函数来处理数组

时间:2017-09-27 10:17:35

标签: php

这是我的简单代码,我无法理解为什么以及如何...

$len = 5;   // total number of numbers
$min = 1;  // minimum
$max = 90;  // maximum
$range = array(); // initialize array
foreach (range(0, $len - 1) as $i) {
    while(in_array($num = mt_rand($min, $max), $range));
    //$range[] = $num;
    list($br1, $br2, $br3, $br4, $br5) = $range;
}
print_r($range);

//echo $br1." ".$br2." ".$br3." ".$br4." ".$br5;

希望在你的帮助下......!谢谢!

2 个答案:

答案 0 :(得分:1)

应写成:

<?php
$len = 5;   // total number of numbers
$min = 1;   // minimum
$max = 90;  // maximum
$range = array(); // initialize array
foreach (range(0, $len - 1) as $i) { // you need to repeat the loop $len times
    // get a new random number in the given range and assign it to $num,
    // do it until the generated number is unique (not present in $range)
    // the loop body is empty, as all the action happens inside its condition
    while(in_array($num = mt_rand($min, $max), $range));

    // append the random number to array
    $range[] = $num;
}
list($br1, $br2, $br3, $br4, $br5) = $range;
echo $br1." ".$br2." ".$br3." ".$br4." ".$br5;

Demo

您的代码的现有版本永远不会更新$range变量(相应的行由于某种原因被注释掉),这就是它无效的原因。

答案 1 :(得分:1)

你需要在你的代码中进行简单的修改。你可以在side循环中分配列表。但是它是循环的站点。您的可变范围数组需要注释

$len = 5;   // total number of numbers
$min = 1;  // minimum
$max = 90;  // maximum
$range = array(); // initialize array
foreach (range(0, $len - 1) as $i) {
      while(in_array($num = mt_rand($min, $max), $range));
       $range[] = $num;
    }
  list($br1, $br2, $br3, $br4, $br5) = $range;
  print_r($br1);
  print_r($br2);

 //echo $br1." ".$br2." ".$br3." ".$br4." ".$br5;