递增嵌套数组值+1,否则设置为1


Increment nested array value +1 else set to 1

我从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语句来检查位置是否是数组,然后在该if语句中检查是否为该位置设置了产品类型?

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

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