简体   繁体   English

如何显示大于零的php数组中的项目

[英]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. 您使用compact()使我相信您正在构建一个多维数组(其中a_inventoryb_inventory ...都是它们自己的包含产品和股票价值的数组),一个foreach可能很不够。 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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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