简体   繁体   中英

How to show items in a php array greater than zero

I am having a hard time wrapping my head around arrays, so far nothing I've read seems to make sense to me so I apologize in advance if this is a silly question? I have built this:

<?php $inv_array = compact("a_inventory", "b_inventory", "c_inventory", "d_inventory");  ?>
            <?php
            foreach($inv_array as $key => $value) {
            echo "$key: $value<br />";
            }

which is displaying the different inventory levels and locations perfectly.What I would like to do next is say if it is in the array and greater than zero echo "In Stock" else "Out of Stock"

Thnaks in advance for any help offered!

This should work for what you've described below

$instock = false;
foreach($inv_array as $value) {
    if($value > 0) {
        $instock = true;
    }
}
echo  ($instock) ? "In Stock" : "Out of Stock";

The way that you are using compact() leads me to believe you are building a multi-dimensional array (where a_inventory , b_inventory ... are all their own arrays with products and stock values), one foreach will most likely not be enough. If you have something like this:

$a_inventory[0]['product'] = 'product1';
$a_inventory[0]['stock'] = '2';

$a_inventory[1]['product'] = 'product2';
$a_inventory[1]['stock'] = '0';

..and so on

$inv_array = compact("a_inventory", "b_inventory", "c_inventory", "d_inventory");

foreach($inv_array as $key => $value) {
    foreach($value as $newKey => $newValue){
        if(($newKey == 'stock') && ($newValue > 0)){
             echo $newKey . " : " . $newValue;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM