在处理数组时,“ foreach”循环会导致“未定义索引”错误。
该数组是从MS Excel生成的,可以与PHP数组函数配合使用。当我使用“ foreach”循环提取数据时,出现“未定义索引”错误,但是当我转储索引值时,我得到了预期的结果。
代码摘录如下:
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 [▶]
答案 0 :(得分:0)
您需要使用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'] : '';
}