猿问

PHP - 如何在数组中插入新元素避免重复?

我想创建一个函数,它将数组$arr_previsioni、值$previsione和$pos指示位置的数字作为输入参数。

该函数应该:

1 - 如果 $previsione 尚不存在,则添加该值。

2 - 如果 input 中给出的值 $previsione 已经存在于数组中,它必须修改 $previsione 的值,使其与所有其他值没有区别,最后将其添加到数组中。



基本上给定一个输入 x 数字,我必须创建一个具有此优先级的唯一数字数组:如果我在输入中给出的 x 数字已经存在于数组中,那么我们需要更改 x 数字(添加或减去某些内容)以使它独一无二。



function aggiungiPrevisione($previsione,$pos,$arr_previsioni){


    echo '<br>';


    // if it is the first element of the array

    if($pos == 1){

        $arr_previsioni['PREVISIONE1'] = $previsione;

        return $arr_previsioni;

    }



    $numero_elementi = count($arr_previsioni);   


    foreach($arr_previsioni as $key=>$value){


        for($i=0; $i <= $numero_elementi+2; $i++){


            // Verifica se esiste

            if (in_array($previsione, $arr_previsioni)){

                // The same number was found in array

                if($previsione  > 45){

                    $previsione = $previsione - 13;

                } else {

                    $previsione = $previsione + 13;

                }

                $previsione = getNumeroGiocabile($previsione); // returns a number from 0 to 90


            } // end checking


        } // end for


    } // end foreach



    // Add $previsione in array

    $arr_previsioni['PREVISIONE'.$pos] = $previsione; // by Vincent Decaux



    return $arr_previsioni;



}


$previsione = makePrevisione(); // return number from 1 to 90

$arr_previsioni = array(); // initially empty

for($pos=1; $pos<=24; $pos++){

   $arr_previsioni = aggiungiPrevisione($previsione,$pos,$arr_previsioni);


var_dump($arr_previsioni);


我创建的函数返回一个包含 24 个元素的数组,但有些元素与其他元素相同。


手掌心
浏览 144回答 1
1回答

慕田峪7331174

看来你正在寻找这样的东西:function aggiungiPrevisione($previsione,$pos,$arr_previsioni)&nbsp;{&nbsp; &nbsp; echo '<br>';&nbsp; &nbsp; // if it is the first element of the array&nbsp; &nbsp; if ($pos == 1) {&nbsp; &nbsp; &nbsp; &nbsp; $arr_previsioni['PREVISIONE1'] = $previsione;&nbsp; &nbsp; &nbsp; &nbsp; return $arr_previsioni;&nbsp; &nbsp; }&nbsp; &nbsp; // Make sure $previsione does not yet exist&nbsp; &nbsp; while (in_array($previsione, $arr_previsioni)) {&nbsp; &nbsp; &nbsp; &nbsp; $previsione = rand(0, 90);&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; // Add $previsione in array&nbsp; &nbsp; $arr_previsioni['PREVISIONE'.$pos] = $previsione;&nbsp;&nbsp; &nbsp; return $arr_previsioni;}请注意,我只更改了此功能的中间部分。我有一个简单的while循环检查值$previsione是否在数组中$arr_previsioni。如果它是一个新的 0 到 90 之间的随机值,则为 生成一个新的随机值$previsione,并再次检查循环条件,直到该值不再存在于数组中。请注意,一旦使用了 0 到 90 之间的所有值,此例程就会失败。我也无法纠正所有其他问题,例如:有一个echo '<br>';用于操作数组的函数。数组中有不需要的字符串键。默认的数字键可能会这样做。阵列的错误初始化例程。我喜欢用英语编程,因为编程语言是英语。混合两种语言不会帮助其他人阅读您的代码,除非他们碰巧是意大利人。顺便说一下,我是荷兰人。你不会喜欢阅读荷兰代码,我敢肯定。与此相反,您的评论是英文的。他们只是为了问题而添加的吗?
随时随地看视频慕课网APP
我要回答