Php 如果已检查数组的所有值,如何引发错误?

Php 如果已检查数组的所有值,如何引发错误?,php,Php,我写了一个小函数,它有一个带有值列表的数组,我希望能够调用这个函数,传递$amount参数,这样它就可以从数组中返回特定数量的信息,所有数据都是随机且唯一的 我被错误检查部分卡住了,如果我们已经烧掉了所有可用的数组列表,我想抛出一个错误 function generate_array(int $amount){ $array = array(0 => array(1), 1 => array(2), 2 => array(3), 3 => array(4));

我写了一个小函数,它有一个带有值列表的数组,我希望能够调用这个函数,传递$amount参数,这样它就可以从数组中返回特定数量的信息,所有数据都是随机且唯一的

我被错误检查部分卡住了,如果我们已经烧掉了所有可用的数组列表,我想抛出一个错误

function generate_array(int $amount){
    $array = array(0 => array(1), 1 => array(2), 2 => array(3), 3 => array(4));
    $count = 1;
    $arr = array();
    $tested = array();

    while($count <= $amount){
        $value = $array[array_rand($array)][0];

        /**
        * Error checking required
        */
        if(!in_array($value, $tested)) array_push($tested, $value);

        // here I need to check if all the values from $array has already been inserted in $tested or checked each one already
        if(count($tested) === $array) throw new \exception('error');    

        /** End of error checks */

        if(in_array($value, $arr)){
           continue; 
        } else {
            array_push($arr, $value);
            $count++;
        }
    }

    return $arr;
}
函数生成_数组(int$amount){
$array=array(0=>array(1),1=>array(2),2=>array(3),3=>array(4));
$count=1;
$arr=array();
$tested=array();

既然($count为什么不在循环之前添加一个错误检查

if (count($array) < $amount) {
    return false;
}

while ($count <= $amount) ...
if(计数($array)<$amount){
返回false;
}

while($count您可以做很多事情,但是如果您希望在while()循环中完成,只需在末尾添加以下内容:

if($count == $amount)
{
throw new \exception('error'); //If you want an error thrown
break; //If you want to exit the loop after the "last go"
}
或者,如果要在循环开始时执行错误检查,请将条件更改为:

if($amount > $count)
{
throw new \exception('error'); //If you want an error thrown
break; //If you want to exit the loop
}

为什么要从循环开始呢?您只需检查被叫方是否请求的数据超过可用数据(
$amount>count($array)
)即可抛出错误,然后执行
shuffle()
数组一次,然后将切片从
0
返回到数组中的
$amount-1
。这样,您只需将数据数组洗牌一次,就不会出现任何无休止的循环。

根据生成的数组是否可以稍微更改,您可以简化整个代码

function generate_array(int $amount){
    $array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4);
    shuffle($array);
    return ($amount <= count($array))?array_slice($array, 0, $amount):false;
}
函数生成_数组(int$amount){
$array=array(0=>1,1=>2,2=>3,3=>4);
洗牌($数组);
返回($amount此

只有
中不存在
$value
时才会将其推入
$tested

这个

如果
$tested
中的元素数与
$array
匹配,则只会
抛出
异常
。因此,您正在比较苹果和桔子,当所有项目都用完并且至少需要使用另一个元素时,您将处于令人讨厌的无限循环中。因此,您需要要比较元素的
计数

if(count($tested) === count($array)) throw new \Exception('error');
您需要在循环块的开始处抛出该值。但由于您从一开始就知道数组中有多少个元素,因此可以在循环之前进行比较,如果不满足条件,则抛出异常:

if ($amount > count($array)) throw new Exception('error');

请注意代码中的大小写,
异常
带有一个大E,这只适用于您,因为您使用的是Windows。如果您在区分大小写的环境中运行此代码,代码将崩溃。

如果“我能做一百万件事”,您就活活烧死我了我甚至想不出1,我应该放弃生活。对不起,我对人不好,我也应该放弃生活(
if(count($tested) === count($array)) throw new \Exception('error');
if ($amount > count($array)) throw new Exception('error');