简体   繁体   中英

foreach loop executing multiple times

I have an array and based on the id I have to insert in different table. But the problem is that array executing multiple times.Suppose I have this id 1 for 3 times, id 2 for 2 times. total data inserting 9 times for id 1 and 4 times for id 2. What am I missing. 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 ). 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);
    }
}
 }
   ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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