Delete repetitions inside While

Asked

Viewed 100 times

4

I have a search that takes the 3 most relevant results in my BD, and then I separate the categories of these 3 results into an array within a While, so it looks something like:

while($x = $x->fetch()){
   $array = explode(',', $x["categoria"]));
   foreach($categoria as $array){
      $->busca no banco de dados cada categoria
      $->while convertendo e retornando os dados relacionados
   }
}

And inside the foreach I want to do the search for the results related to the category of the array in question, but when a result fits in more than one category the same comes duplicated in the list, my doubts are: How can I eliminate these duplicates? It’ll be heavy 3 loops of repetitions inside each other?

  • Yes, it gets heavy. I recommend doing the whole query, receiving all the data and then, get what you need.

  • I can do 3 different searches, picking 1 relevant result at a time, so I decrease 1 loop of repetition, but there’s still the problem of repetitions inside the foreach

  • Well... I was going to edit your code... but I wanted you to look at your foreach: Something is not missing? --- foreach ($array as $categoria)

  • yes I only realized after I posted, but this is just an example code, in the original is with the "as"

  • 1

    Take a look at the PHP array_map() function, you might be able to optimize the code a little, since it’s faster than iterating in PHP. Another idea is to place categories in an Array and search for related data using the database’s IN clause, rather than searching each of them separately in each iteration.

  • Newton if I use a direct IN in the array without foreach or anything, the php of the error of "Array to Conversion to string"

Show 1 more comment

1 answer

1

Hello. You can resolve directly in your SQL query by adding a GROUP BY by the code of the element you seek. Much simpler and faster.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.