密钥存在时如何解决 'Undefined index' 错误?

How do I solve 'Undefined index' error when the key exists?

当我操作数组时,

"foreach" 循环导致 'Undefined Index' 错误。

该数组是从 MS Excel 生成的,可以与 PHP 数组函数配合使用。当我使用 "foreach" 循环提取数据时,出现 'Undefined Index' 错误,但是当我转储索引值时,我得到了想要的结果。

代码摘录如下:

    foreach ($membership_data as $data){
        //dd($data["Gender"]);
        if($data["Gender"]=='Male') {
            $males_dates_of_birth[] = $data['DateofBirth'];
        } elseif ($data["Gender"]=='Female'){
            $females_dates_of_birth[] = $data['DateofBirth'];
        } else {
            $erroneous_gender_dates_of_birth[] = $data['DateofBirth'];
        }
    }

如何解决?

否则,有没有更好的方法来获取包含不同性别的出生日期的三个数组?示例数据数组如下。

array:100 [▼
  6 => array:15 [▼
    "MemberNumber" => "48490"
    "Surname" => "Wuckert"
    "FirstName" => "Clement"
    "OtherNames" => "Dr. Monique Murazik II"
    "DateofBirth" => "1968-08-4"
    "DateEmployed" => "1988-08-04"
    "DateJoinedScheme" => "1968-08-4"
    "Gender" => "Female"
    "DocumentType" => "National ID"
    "DocumentNumber" => "a370523307a"
    "KRAPIN" => "a459831176c"
    "NSSFNumber" => "a526026924k"
    "TelephoneNumber" => "722136702"
    "EmailAddress" => "annie99@yahoo.com"
    "TelephoneNumberCountry" => "Kenya"
  ]
  7 => array:15 [▶]
  8 => array:15 [▶]
  9 => array:15 [▶]
  10 => array:15 [▶]
  11 => array:14 [▶]

您需要使用 array_key_exists

检查数组中是否存在键
if(array_key_exists('Gender', $data) && $data["Gender"]=='Male') {
    $males_dates_of_birth[] = array_key_exists('DateofBirth', $data)  ? $data['DateofBirth'] : '';
} elseif (array_key_exists('Gender', $data) && $data["Gender"]=='Female'){
    $females_dates_of_birth[] = array_key_exists('DateofBirth', $data)  ? $data['DateofBirth'] : '';
} else {
    $erroneous_gender_dates_of_birth[] = array_key_exists('DateofBirth', $data)  ? $data['DateofBirth'] : '';
}