How to integrate two for/foreach loops in following scenario?

前端 未结 5 456
忘了有多久
忘了有多久 2021-01-27 06:39

I\'m having two arrays as follows:

$user_ids = Array
(
    [0] => 159a8a6f1c00c5c4d5d0daaab2aa4227
    [1] => a39777761f7816031aec676c80c3a8ad
    [2] =>         


        
相关标签:
5条回答
  • 2021-01-27 06:53

    You don't need a nested foreach to do this. It's easy to do with array_combine(). Create a new array by using ids as keys and statuses as values, and then loop through the array and call the function as you need it:

    $array = array_combine($user_ids, $user_statuses);
    $array = array_map('trim', $array); // remove whitespaces
    foreach ($array as $id => $status) {
        if($status == 'disable') {
            $objAdminUsers->UpdateUserStatus($id, $status); 
            $count++;
        }
    }
    

    Demo!

    0 讨论(0)
  • 2021-01-27 06:57

    Maybe like this?

    $user_ids = explode(',', $request['items']);
      $user_statuses = explode(',', $request['user_status']);
      foreach ($user_statuses as $key => $user_status) { 
        if(user_status=='disable') {
          $objAdminUsers->UpdateUserStatus($user_ids[$key], $user_status); 
        }
      }
    
    0 讨论(0)
  • 2021-01-27 07:05

    You're close. Since both arrays contain an even amount of values, you can get the $key while looping the elements as such:

     $user_ids = explode(',', $request['items']);
      $user_statuses = explode(',', $request['user_status']);
      $count = 0;
      foreach ($user_ids as $key => $user_id) {
        // $key contains the number between the brackets
          if($user_statuses[$key]=='disable') {
            $objAdminUsers->UpdateUserStatus($user_id, $user_statuses[$key]); 
        $count++;
          }
        }
      }
    

    This way you don't need a second foreach loop but you simply read the other array simultaneously

    0 讨论(0)
  • 2021-01-27 07:08

    You just need one foreach, like so:

      $user_ids = explode(',', $request['items']);
      $user_statuses = explode(',', $request['user_status']);
      $count = 0;
      foreach ($user_ids as $key => $user_id) {
          if($user_status[$key]=='disable') {
            $objAdminUsers->UpdateUserStatus($user_id, $user_status[$key]); 
            $count++;
          }
      }
    
    0 讨论(0)
  • 2021-01-27 07:09

    Refer: http://phpfiddle.org/main/code/8ni-kjz

    while ($match = current($user_status)) {
        if ($match == 'disable') {
            $id = key($user_status);
            objAdminUsers->UpdateUserStatus($user_ids[$id], $user_status[$id]); 
                    $count++;
        }
        next($user_status);
    }
    
    0 讨论(0)
提交回复
热议问题