我有这个代码:
$actors = explode(",",$this->input->post('movie_actors', true));
foreach ($actors as $value) {
$actor['name'] = $value;
}
我当前的输出是
array(1) { ["name"]=> string(6) "Actor4" }
但是变量$actors是这样的actors列表:Actor1、Actor2、Actor3、Actor4
为什么只得到最后一个元素?
foreach ($actors as $value) { $actor['name'] = $value; }
您正在获取最后一个元素,因为数组$actor具有单个索引"name"。每次foreach循环运行$array['name']时,都会覆盖索引值。所以像这个一样更新你的循环
foreach ($actors as $value) { $actor[]['name'] = $value; }
你会得到所有的演员。
我已经用以下代码解决了这个问题:
$actors = explode(",",$this->input->post('movie_actors', true));
foreach ($actors as $value) {
$data[]['name'] = $value;
}
$this->db->insert_batch('actors', $actor);
这把钥匙是insert_batch,而不仅仅是insert!