我真的在寻找相当长的一段时间,但我不知道该改变什么。我的PHP代码获取一个数组,我希望它插入到mysqlDB中。问题是它只运行一次foreach循环。为什么不运行?
public function insert_tags($projektID, $tags) {
print_r($tags);
foreach($tags as $tag)
$this->db->set('name', $tag);
$this->db->insert('tags');
echo $tag;
$tag_ID = $this->db->insert_id();
echo $tag_ID;
if ($tag_ID != 0) {
$this->db->set('id', $projektID);
$this->db->set('tag_ID', $tag_ID);
$this->db->insert('hat_tags');
}
}
回声:
Array
(
[0] => tag1
[1] => tag2
)
tag2 147
没有进一步的错误。谢谢你的帮助!
答案 0 :(得分:4)
foreach循环需要括在大括号{}中,否则它将在foreach语句之后只循环一行
答案 1 :(得分:2)
您需要将它们括在{}括号中,否则它将循环它旁边的第一行。使用以下代码
public function insert_tags($projektID, $tags) {
print_r($tags);
foreach($tags as $tag){
$this->db->set('name', $tag);
$this->db->insert('tags');
echo $tag;
$tag_ID = $this->db->insert_id();
echo $tag_ID;
if ($tag_ID != 0) {
$this->db->set('id', $projektID);
$this->db->set('tag_ID', $tag_ID);
$this->db->insert('hat_tags');
}
}
}
或者你可以将它与endforeach一起使用
public function insert_tags($projektID, $tags) {
print_r($tags);
foreach($tags as $tag):
$this->db->set('name', $tag);
$this->db->insert('tags');
echo $tag;
$tag_ID = $this->db->insert_id();
echo $tag_ID;
if ($tag_ID != 0) {
$this->db->set('id', $projektID);
$this->db->set('tag_ID', $tag_ID);
$this->db->insert('hat_tags');
}
endforeach;
}
希望这有助于你