简体   繁体   English

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

[英]php - Why foreach only runs once?

I really was searching quite some time but I do not know what to change. 我确实在搜索了很长时间,但我不知道要更改什么。 My php code gets an array and I want it to insert into a mysqlDB. 我的PHP代码获取一个数组,我希望将其插入到mysqlDB中。 Problem is that it only runs the foreach loop once. 问题是它只运行一次foreach循环。 Why is it not running? 为什么不运行?

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');
        }
}

It echos: 它呼应:

Array
(
    [0] => tag1
    [1] => tag2
)
tag2 147

No further error. 没有进一步的错误。 Thanks for any help! 谢谢你的帮助!

foreach循环需要用大括号{}括起来,否则它将仅在foreach语句之后循环一行

You need to enclose them in {} brackets otherwise it will loop the first line next to it. 您需要将它们括在{}括号中,否则它将循环其旁边的第一行。 Use the code below 使用下面的代码

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');
        }
    }

}

Or you can use it with endforeach 或者您可以将其与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;

}

Hope this helps you 希望这对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM