简体   繁体   English

foreach 循环执行多次

[英]foreach loop executing multiple times

I have an array and based on the id I have to insert in different table.我有一个数组,根据 id 我必须插入到不同的表中。 But the problem is that array executing multiple times.Suppose I have this id 1 for 3 times, id 2 for 2 times.但问题是数组执行多次。假设我有这个 id 1 3 次,id 2 2 次。 total data inserting 9 times for id 1 and 4 times for id 2. What am I missing.总数据为 id 1 插入 9 次,为 id 2 插入 4 次。我错过了什么。 My code我的代码

if (!empty($this->request->data['other_source_options'])) {
    foreach ($this->request->data['other_source_options'] as $value) {
      if ($value == 1) {
           $this->__function_name_1(1);
         }
      if ($value == 2) {
           $this->__function_name_2(2);
          }
      if ($value == 3) {
          $this->__function_name_3(3);
          }
      if ($value == 4) {
          $this->__function_name_4(4);
        }
    }
}

You can use array_unique function (Refer from here ).您可以使用 array_unique 函数(请参阅此处)。 You can use below code:您可以使用以下代码:

 <?php
  if (!empty($this->request->data['other_source_options'])) {
  $arrUnique = array_unique($this->request->data['other_source_options']);

foreach ($arrUnique as $value) {
  if ($value == 1) {
       $this->__function_name_1(1);
     }
  if ($value == 2) {
       $this->__function_name_2(2);
      }
  if ($value == 3) {
      $this->__function_name_3(3);
      }
  if ($value == 4) {
      $this->__function_name_4(4);
    }
}
 }
   ?>

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

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