我想将数组中的多个项目插入到foreach
的数据库中。我收到一个错误
Message: Undefined offset
。有人可以帮我找出导致它的原因吗?
错误:
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Line Number: 127
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Line Number: 128
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Line Number: 129
PHP:
<?php
$guide_input = $this->input->post('guide');
$airline_input = $this->input->post('airline');
$name_r_input = $this->input->post('name_r');
$units_input = $this->input->post('units');
$price_change_input = $this->input->post('price_change');
$guide = array();
$airline = array();
$date_go = array();
$date_back = array();
$residence = array();
foreach ($guide_input as $idx => $name) {
$guide[] = array(
'name_guide' => $guide_input[$idx], //Line Number: 121
);
$airline[] = array(
'name_airline' => $airline_input[$idx], //Line Number: 124
);
$residence[] = array(
'name_r' => $name_r_input[$idx], //Line Number: 127
'units' => $units_input[$idx], //Line Number: 128
'price_change' => $price_change_input[$idx], //Line Number: 128
);
};
$data = array(
'json1' => json_encode($residence),
'json2' => json_encode($airline),
'json3' => json_encode($guide),
);
$this->db->insert(tableName, $data);
答案 0 :(得分:1)
上面的代码假设所有输入数组(如$ airline_input,$ date_go_input等等)将具有与$ guide_input相同数量的元素。我的猜测是他们不这样做。
为了使代码正确并且运行没有错误,你应该检查:
count($guide_input) == count($airline_input)
&& count($guide_input) == count($date_go_input)
// ... and so on... //
答案 1 :(得分:0)
我认为您应该检查guide_input
,airline_input
,依此类推。每个阵列都有相同的键?