简体   繁体   English

for循环中未定义的偏移量错误

[英]Undefined offset error in for loop

This code helps me find the minimum of certain sums, so I set a function as the one below: 这段代码可以帮助我找到某些总和的最小值,因此我将一个函数设置为以下函数:

 function GetMin($s)
    {

        for($j=1;$j<=count($s)-1;$j++)
        {
            $min=$s[1];
            if($s[$j] < $s[$j+1] && $s[$j] < $min)
            {
                $min=$s[$j];
            }
    else {continue;}        
        }
        echo $min;
    }

$enc=".129.25.24.154.546.214.142.254.256";
$ar=explode(".",$enc);
for($i=0;$i<count($ar)-1;$i+=3)
{
    $s[$i+1]=$ar[$i+1]+$ar[$i+2]+$ar[$i+3];
    echo $s[$i+1]."<br>";
}


GetMin($s)

The code should work this way: 该代码应以这种方式工作:

Calculates the sum of every 3 terms of the array and store it in a term of another array called "s", the code is working well, until I try to find the minimum, it prints the minimum but with the error below: 计算数组的每3个项的总和,并将其存储在另一个名为“ s”的数组的项中,代码运行良好,直到我尝试找到最小值,它打印出最小值,但出现以下错误:

Notice: Undefined offset: 2 in C:\\Program Files (x86)\\Apache Software Foundation\\Apache2.2\\htdocs\\decrypt.php on line 9 Notice: Undefined offset: 2 in C:\\Program Files (x86)\\Apache Software Foundation\\Apache2.2\\htdocs\\decrypt.php on line 9 Notice: Undefined offset: 3 in C:\\Program Files (x86)\\Apache Software Foundation\\Apache2.2\\htdocs\\decrypt.php on line 9 178 注意:第9行的C:\\ Program Files(x86)\\ Apache Software Foundation \\ Apache2.2 \\ htdocs \\ decrypt.php中未定义的偏移量:2注意:C:\\ Program Files(x86)\\ Apache软件中的未定义偏移量:2第9行上的Foundation \\ Apache2.2 \\ htdocs \\ decrypt.php注意:第9 178行上的C:\\ Program Files(x86)\\ Apache Software Foundation \\ Apache2.2 \\ htdocs \\ decrypt.php中未定义的偏移量:3

It looks like you're trying to get the lowest value in an array of values, so I've changed your GetMin() function to work with the non-consecutively indexed array that you create prior to calling GetMin() . 看起来您正在尝试获取值数组中的最低值,因此我更改了GetMin()函数,使其与在调用GetMin()之前创建的非连续索引数组一起使用。 This should work for you: 这应该为您工作:

<?php
function GetMin($s){
    $min = NULL;
    foreach($s as $v){
        if(is_null($min)){
            $min = $v;
        } elseif($v < $min){
            $min = $v;
        }
    }
    return $min;
}
$enc = ".129.25.24.154.546.214.142.254.256";
$ar = explode(".",$enc);
$ar_count = count($ar);
for($i=0;$i<$ar_count-1;$i+=3)
{
    $s[$i+1]=$ar[$i+1]+$ar[$i+2]+$ar[$i+3];
    echo $s[$i+1]."<br>";
}


echo GetMin($s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM