Php 递增数组';s值导致日志中出现警告

Php 递增数组';s值导致日志中出现警告,php,arrays,Php,Arrays,我正在尝试创建一个数组,其中包含我们根据位置和讲师提供的每门课程的计数。下面是示例代码 $courseCnt = array(); foreach($courseList as $course){ $courseCnt[$course['location']][$course['instructor']] += 1 } 这段代码正确地创建了数组并显示得很好,但我收到了一系列警告,如: 位置的未识别索引“Orlando”,未识别索引“John” “史密斯”为讲师 我发现,如果我只是将

我正在尝试创建一个数组,其中包含我们根据位置和讲师提供的每门课程的计数。下面是示例代码

$courseCnt = array();
foreach($courseList as $course){
      $courseCnt[$course['location']][$course['instructor']] += 1
}
这段代码正确地创建了数组并显示得很好,但我收到了一系列警告,如:

位置的未识别索引“Orlando”,未识别索引“John” “史密斯”为讲师

我发现,如果我只是将其设为=1而不是+=1,警告就会消失,但这当然会使位置/讲师1的每门课程都不好

我的下一个想法是检查它是否存在,如果不存在,将其设为1,如果存在+=1。这里有一个例子

if(isset($courseCnt[$course['location']][$course['instructor']]){
     $courseCnt[$course['location']][$course['instructor']] += 1
}else{
     $courseCnt[$course['location']][$course['instructor']] = 1
}
这将导致致命错误:

无法将字符串偏移量用作数组

$course数组结构只是从sql中提取的二维数组

样本:

courseID   location   instructor
1          Orlando    John Smith
2          Detroit    Bill Murray

在检查新版本代码的第一行中的讲师之前,您没有检查该位置是否存在。您需要检查它是否存在,如果不存在,则在
$courseCnt
数组中创建它(作为空数组)。之后,您可以检查讲师:

// Initialise the empty array
$courseCnt = array();

// Create location if not in array
if( ! isset($courseCnt[$course['location']])) { 
  $courseCnt[$course['location']] = array();
}

// Either increment the instructor or create with initial value of 1
if ( isset($courseCnt[$course['location']][$courseCnt[$course['instructor']]]) ) {
  $courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
  $courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}
这里有很多方括号,因此如果使用PHP的
array\u key\u exists
()而不是
isset
,您可能会发现更容易阅读:

// Initialise the empty array
$courseCnt = array();

// Create location if not in array
if( ! array_key_exists($course['location'], $courseCnt)) { 
  $courseCnt[$course['location']] = array();
}

// Either increment the instructor or create with initial value of 1
if ( array_key_exists($course['instructor'], $courseCnt[$course['location']]) ) {
  $courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
  $courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}

发布您的数组结构
$course
array structure.from-或编辑并添加的课程structure@Sean我已经看过这些样本了,我觉得它们不适合我的情况。如果我试着检查它是否设置好了,我才会遇到这个问题。这不是我最初的问题