dqpu4988 2015-02-10 13:41
浏览 398
已采纳

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

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. Problem is that it only runs the foreach loop once. 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!

  • 写回答

2条回答 默认 最新

  • dousha2020 2015-02-10 13:44
    关注

    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

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭