【问题标题】:php - Why foreach only runs once?php - 为什么 foreach 只运行一次?
【发布时间】:2015-04-10 13:43:57
【问题描述】:

我确实搜索了很长时间,但我不知道要更改什么。我的 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

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

【问题讨论】:

    标签: php codeigniter activerecord


    【解决方案1】:

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

    【讨论】:

    • 实际上不需要用大括号括起来,您可以使用另一种语法,例如:foreach(): endforeach;
    【解决方案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;
    
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多