如何在循环中中断索引数组并在php中使用

我在索引数组中有两个值(bookingId),现在我想使用这些值更新查询,但现在无法在循环中中断数组,我想运行更新查询(根据数组中的计数值)这是我的代码,我错在哪里?


$bookingIds; // contaning two values 176,190

$counts = count($bookingIds);  // counting array values

for ($x = 1; $x <= $counts; $x++) 

    {

        $data = array('approved' => "1");

        $this->db->where('bookingId', $bookingIds);

        $this->db->update('notifications', $data);

    }


达令说
浏览 108回答 3
3回答

慕斯709654

我认为你应该在循环时提及数组的索引。并且你$x必须从0$bookingIds; // contaning two values 176,190$counts = count($bookingIds);&nbsp; // counting array valuesfor ($x = 0; $x < $counts; $x++)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $data = array('approved' => "1");&nbsp; &nbsp; &nbsp; &nbsp; $this->db->where('bookingId', $bookingIds[$x]);&nbsp; &nbsp; &nbsp; &nbsp; $this->db->update('notifications', $data);&nbsp; &nbsp; }

慕莱坞森

使用 foreach 来重构上述内容以消除整个索引问题将是$data = array('approved' => "1");foreach ($bookingsIds as $bookingId ){&nbsp; &nbsp; $this->db->where('bookingId', $bookingId);&nbsp; &nbsp; $this->db->update('notifications', $data);}

慕神8447489

看起来你正在使用一个框架;如果它提供了一个whereIn()方法,使用它会更有效(运行更少的 SQL 查询):$data&nbsp;=&nbsp;['approved'&nbsp;=>&nbsp;'1'];$this->db &nbsp;&nbsp;&nbsp;&nbsp;->whereIn('bookingId',&nbsp;$bookingIds) &nbsp;&nbsp;&nbsp;&nbsp;->update('notifications',&nbsp;$data);(请注意,您不能将数千个值放入这样的“where in”子句中,因为查询会很大。就我个人而言,我会分块处理此类内容,例如每个查询 500 条记录。)(另外,如果“where in”数组(此处为 )为空,请确保不会发生错误$bookingIds。这是一种特殊情况,框架必须正确处理。)
打开App,查看更多内容
随时随地看视频慕课网APP