我的头撞在桌子上,试图弄清楚为什么这个PHP代码会导致这个错误:Undefined index: arr
。我使用的是Laravel,这段代码在它的外部就像黄金一样工作,但在Laravel内部,它返回了未定义的索引错误。
这是代码:
function set_pilots_array($line_array)
{
$airports = $this->airports;
$pilots = $this->pilots;
foreach($airports as $airport)
{
if($airport == $line_array[11] || $airport == $line_array[13])
{
if($airport == $line_array[11])
{
$deparr = "dep";
}
if($airport == $line_array[13])
{
$deparr = "arr";
}
$this->pilots[$deparr][] = array($line_array[0], $line_array[11], $line_array[13], $line_array[7], $line_array[5], $line_array[6], $line_array[8]);
}
}
}
function get_pilots_count()
{
$count = count($this->pilots['dep']) + count($this->pilots['arr']);
return $count;
}
这与我的另一个问题有关:抓取并分解数据它使用以下代码从数据文件中提取数据:
elseif($data_record[3] == "PILOT")
{
$code_obj->set_pilots_array($data_record);
}
哪个后来这样做:
$code_count = $code_obj->get_pilots_count();
您没有设置$this->pilots['arr']
。换句话说,如果你看var_dump($this->pilots);
的输出,你会发现没有arr
键值对。我建议你这个修复:
$count = count((isset($this->pilots['dep']) ? $this->pilots['dep'] : array())) + count((isset($this->pilots['arr']) ? $this->pilots['arr'] : array()));
事实上,这不是一个修复-这更像是一个黑客。为了使您的代码正确,我建议您设置$pilots['arr']
和$pilots['dep']
值的默认值:
function set_pilots_array($line_array)
{
$airports = $this->airports;
$pilots = $this->pilots;
foreach (array('dep', 'arr') as $key)
{
if (!is_array($pilots[$key]) || empty($pilots[$key]))
{
$pilots[$key] = array();
}
}
// ...
}
代码太少,无法真正弄清楚发生了什么,但基于我所看到的:
if($airport == $line_array[13])
这个条件永远不会被满足,所以$deparr = "arr";
永远不会发生,因为这个
count($this->pilots['arr']);
正在给出未定义的索引错误
您可以通过以下方式轻松抑制这种情况:
$count = count(@$this->pilots['dep']) + count(@$this->pilots['arr']);
您的问题是直接访问所有索引,而不首先检查它们是否存在。
假设在laravel中有什么东西导致数组没有被填充。
为了解决这个问题,您应该使用foreach
迭代数组,或者在访问它之前执行if(!empty($line_array[13])) {}
。