A
A
adrenalinruslan2018-03-30 15:53:37
PHP
adrenalinruslan, 2018-03-30 15:53:37

Lots of foreach is it ok?

In general, as I understand it, you need to make as few queries to the database as possible, and I decided to send a request to the database once and write the answer to array 1, and only then from array 1 everything you need to get. And now I have such a question, I made the following code (Ps I immediately say to the name of the variables, do not pay attention, I'm only learning and this is for the test):

$catalog = 1; // Для теста 

$qa_products = $link->query('SELECT * FROM `products`');
  $array_products = array();
  while($w_products = $qa_products->fetch(PDO::FETCH_ASSOC)) {
    $array_products[] = $w_products;
  }

// В другом месте, код ( Нужно сделать поиск id каталога по массиву 1, если такой каталог найден, то он записывается в другой массив 2, потом массив 2 проверятся на кол-во строк, если их 0, то пишет что аккаунтов не найдено, если их >=1, то через foreach все они выводятся):

$get_catalog_1 = array();

              foreach($array_products as $for_products_1) {
                if($for_products_1['catalog_id'] == $catalog) {
                  $get_catalog_1[] = $for_products_1;
                }
              }

              if(count($get_catalog_1) >= 1) {
                foreach($get_catalog_1 as $set_catalog_1): ?>
                  <p><?php echo $set_catalog_1['title']; ?></p>
                <?php endforeach;
              } else {
                ?>
                  <p>В данной категории нет аккаунтов</p>
                <?php
              }

If this code is run, then everything works. But is it okay to do it this way? Is it normal that I use arrays and foreach so much? And if not right, how would it be better to do it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Azim Kurt, 2018-03-30
@Symphony

SELECT * FROM `products` WHERE catalog_id = 1
This query will minify the code.

E
Eugene, 2018-03-30
@e_snegirev

if I understand correctly, you need an array_filter so as not to go over extra elements

N
Nurlan, 2018-03-30
@daager

Think:
much better than what you wrote. The code will be 3-4 times shorter and clearer.
In terms of speed:
- on a small table, the difference tends to zero
- on a millionth, MySQL with indexes is better.

D
Dmitry Entelis, 2018-03-30
@DmitriyEntelis

1. Search logic is better to take out in sql
2. Where it is possible to use built-in functions - it is better to use built-in functions.
3. A cycle to output something is normal. It is bad to make queries in sql in a loop

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question