Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Skipping a multidimensional Array in a foreach loop PHP

I want to loop an array variable in a for-each loop or any other way you suggest . and when looping if an array has two or more identical items/values the loop should skip the data and continue in with the next data .

$users = array ( array('user1', id , email),
                 array('user2', id , email),
                 array('user3', id , email),
                 array('user4', id , email)

foreach ($users as $key) {

  // do something for each user
  // if from arrays user1 , user2 , user3 , user4 there are some identical data .. 
  // skip that user and continue with another user 
  // then return results and number of users skipped          
}

Example : if in array $users user1 has an email address/id same as user3 skip user3 and continue with user4

Hope you have got my point as I'm not so good in English

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One simple way would be to just put all the email addresses that came up so far while looping through the array into another array, and check if the current email is in that already:

$email_addresses_processed_so_far = array();
foreach ($users as $key) {
  if(in_array($key[2], $email_addresses_processed_so_far)) {
    continue;
  }
  $email_addresses_processed_so_far[] = $key[2]; // put email address into array
  // additional processing here
  // …
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...