php - 为什么 foreach 只运行一次?

php - Why foreach only runs once?

我真的找了好久,但我不知道要改什么。我的 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

没有进一步的错误。感谢您的帮助!

foreach循环需要用大括号{}括起来,否则只会在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');
        }
    }

}

或者您可以将它与 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;

}

希望对您有所帮助