Answer the question
In order to leave comments, you need to log in
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
}
Answer the question
In order to leave comments, you need to log in
SELECT * FROM `products` WHERE catalog_id = 1
This query will minify the code.
if I understand correctly, you need an array_filter so as not to go over extra elements
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.
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 questionAsk a Question
731 491 924 answers to any question