增量嵌套数组值+1 else设置为1

时间:2016-04-04 03:49:42

标签: php mysql arrays

我正在从mysql表中提取产品列表,并且我在php数组中将每个位置的总产品类型数量相加。我知道我可以通过mysql做到这一点,但它比这更复杂,所以让我们说一个php数组是我唯一的选择!

mysql查询将设置为数组$ products设置如下:

Index         product_type       location
0          Chevy              South Bend
1          Ford               Aurora
2          Chevy              South Bend
3          Chevy              Aurora

然后我有以下代码来设置我将用于显示的数组:

$myProducts = array();
if(is_array($products){
    foreach($products as $product){
      if(isset($myProducts['location']['product_type'])){
           $myProducts['location']['product_type'] ++;
      }else{
           $myProducts['location']['product_type'] = 1;
      }
    }
}

此方法在显示方面起作用,但我会遇到如下错误:

PHP Notice:  Undefined index: South Bend

我已尝试在警告中执行以下相同的结果。

if(is_array($myProducts['location']) && isset($myProducts['location']['product_type'])){

}

是否存在一种方法,我不需要执行嵌套if语句来检查location是否为数组,然后在if语句中检查是否为该位置设置了产品类型?

1 个答案:

答案 0 :(得分:0)

在foreach的第一行之后添加,以创建数组并停止通知

if(!isset($myProducts['location']['product_type'])){$myProducts['location']['product_type']=0}