你好,我在这里遇到问题,我想像这样在php的数组声明中创建一个if语句
foreach($data as $d){
$temparray = [
if($d['STAT'] =='STUND'){
'stat_acc' => $stat_stund_acc,
'stat_blok' => $stat_stund_blok
}else{
'stat_acc' => $stat_acc,
'stat_blok' => $stat_blok
}
'other_data1' => $other_data1
'other_data2' => $other_data2
];
}
但是在我的vscode中有一个警告错误
答案 0 :(得分:1)
为什么不喜欢这个?
$temparray = [];
if($d['STAT'] =='STUND'){
$temparray = [
'stat_acc' => $stat_stund_acc,
'stat_blok' => $stat_stund_blok,
'other_data1' => $other_data1,
'other_data2' => $other_data2
];
}
else{
$temparray = [
'stat_acc' => $stat_acc,
'stat_blok' => $stat_blok,
'other_data1' => $other_data1,
'other_data2' => $other_data2
];
}
答案 1 :(得分:1)
您可以按照@rafalrozek所说的用一般的if
来保护整个事情,或者也可以只保护自己想要的东西:
foreach ($data as $d) {
$temparray = [
'other_data1' => $other_data1,
'other_data2' => $other_data2,
];
if ($d['STAT'] == 'STUND') {
$temparray['stat_acc'] = $stat_stund_acc;
$temparray['stat_blok'] = $stat_stund_blok;
} else {
$temparray['stat_acc'] = $stat_acc;
$temparray['stat_blok'] = $stat_blok;
}
}
此外,只要条件检查不太昂贵,就可以使用三元:
foreach ($data as $d) {
$temparray = [
'stat_acc' => $d['STAT'] == 'STUND' ? $stat_stund_acc : $stat_acc,
'stat_blok' => $d['STAT'] == 'STUND' ? $stat_stund_blok : $stat_blok,
'other_data1' => $other_data1,
'other_data2' => $other_data2,
];
}