0

我正在尝试使用此代码提取数组,但它给出了该错误。但是,如果我从代码中删除 while 块并且只给出索引,它就可以工作。这是代码。

    //This function gives error: Notice: Undefined offset: 1 in .......
//but if i delete while block and only write print $type[$i]; it works.

public function checkMimeType(){
        echo '<pre>';
        $i = 0;
        $type = array();
            foreach($this->_sourceFile as $key){

                $type= $key['type'];

            }
        while($i <= count($type))
        {
            print $type[$i].'<br>';
            $i++;
        }

    }
4

3 回答 3

0

计数不等于最后一个索引。

数组[x, y, z]的计数为3,但最后一个索引为2

因此,在您的 while 循环中,您不能运行直到<= count,而只能运行< count。何时$i成为count索引已经超出范围。

于 2013-11-14T23:40:46.800 回答
0

在您的第一个循环中,您不是向数组添加值,而是$type每次都覆盖变量。尝试这个:

$type[] = $key['type'];

编辑:还有@thst 所说的

于 2013-11-14T23:41:01.870 回答
0

你经常循环一次;)

索引号从零开始。如果数组中有一个元素,则定义的唯一索引因此为 0。count()将返回 1。如果循环 'till $i<= 1,它将停止在$i = 1. 没有 ID 为 1 的元素。

所以,相反,使用while($i < count($type))

于 2013-11-14T23:41:59.153 回答