Вопрос

I have a php foreach loop that is displaying all my products on my store. The code looks like this:

 <?php foreach ($products as $product) { ?>

// getting products here

<?php } ?>

There are some products I wish not to show up in that loop, that I have the id's for, so I edited the Foreach loop like this:

<?php $ids = array(564,365,66,234,55); ?>

<?php foreach ($products as $product) { ?>
    <?php if(in_array($product['product_id'],$ids)) { ?>
          //getting products here
        <?php } ?>
<?php } ?>

This did just the opposite of what I wanted to do. I kinda knew it would. But I figured there is some way to reverse this and hide only those products. I was wondering if there was away to remove those products ids from the product array, and then continue the php loop getting all the other products. Any ideas? Thanks!

Это было полезно?

Решение

Simply negate the condition:

if(!in_array($product['product_id'],$ids))

Другие советы

You need to use the logical NOT operator, ! to only execute your code if the ID is NOT in the list.

<?php $ids = array(564,365,66,234,55); ?>

<?php foreach ($products as $product) { ?>
    <?php if(!in_array($product['product_id'],$ids)) { ?>
         // do operation
    <?php } ?>
<?php } ?>

Just use the !

So we are saying if the ids are not in the array it's cool to display them.

<?php $ids = array(564,365,66,234,55); ?>
<?php foreach ($products as $product): ?>
<?php if(!in_array($product['product_id'],$ids)):?>
  //show products that are not in array
<?php endif ?>
<?php endforeach ?>

If you plan on working with this reduced set later, you could use array_filter.

$filtered = array_filter($products, function($x) use($ids) { 
    return !in_array($x['product_id'], $ids); 
});

foreach ($filtered as $product) {
    // do operation
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top