数组php中存在未定义的偏移量错误


Undefined offset error in array php

当我运行下面的代码时,我得到了这个消息
注意:第50行上C:''wamp''www''cbir''index.php中的未定义偏移量:226

我认为这几行代码导致了错误$reds[$r]++;$greens[$g]++;$blues[$b]++;

    $reds = array();
    $blues = array();
    $greens = array();
    $freqr = array();
    $freqb = array();
    $freqg = array();
    $info = getimagesize($_FILES['image']['tmp_name']);
    $width = $info[0];
    $height = $info[1];
    $totalpixels = $width * $height;
    $img = imagecreatefromjpeg($_FILES['image']['tmp_name']);
    if ($img) {
         for ($i = 0; $i < $height; $i++) {
        for ($j = 0; $j < $width; $j++) {
            $rgb = imagecolorat($img, $j, $i);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            // Add counts to our histogram arrays for each color.
            $reds[$r]++;
            $greens[$g]++;
            $blues[$b]++;
        }
    }

您初始化了一个空的$reds数组,但没有定义$reds[$r](例如)。代替:

$reds[$r]++;

用途:

if(!isset($reds[$r])) {
  $reds[$r] = 0;
}
$reds[$r]++;

类似于$greens$blues

或者,由于将使用的密钥从0到255,您可以首先使用初始化数组

$reds = array_fill(0, 256, 0); // instead of using: $reds = array();