当 PHP array_key_exists 为 FALSE 时,为什么我不能添加键和值?

Why can't I add a key and value when PHP array_key_exists is FALSE?

我只是想将一组键和值添加到数组中,当且仅当它们不在数组中时。当它们不在数组中时,我需要添加 d1 到 d20,

这是我的代码。

print_r($demos_keys)

Array
(
    [0] => d01
    [1] => firstname
    [2] => lastname
    [3] => email
    [4] => d02
    [5] => d03
    [6] => partnerid
)
$counter=0;
foreach ($csvdata as $row) {
    if ($counter > 0) {
    $rowdata_tmp = explode(',', trim($row));
    $rowdata_tmp['partnerid'] = $partnerid;
    $rowdata[] = array_combine($demos_keys, $rowdata_tmp);


//Fails to add 'd04'
        // if(isset($rowdata['d04'])){
        // $x=1;
        // } else {
            // $rowdata['d04']='';
        // }

//Fails to add 'd04'
        // if(isset($rowdata['d04'])){
        // $x=1;
        // } else {
            // $row['d04']='';
        // }
        
//Fails 
    if (array_key_exists('d04',$rowdata)==FALSE) {$rowdata['d04'] = '';}
    }

//Fails 
    if (array_key_exists('d04',$rowdata)==FALSE) {$row['d04'] = '';}
    }


    $counter = $counter + 1;
    
}

print_r($rowdata);

Array
(
    [0] => Array
        (
            [d01] => 1
            [firstname] => Fred
            [lastname] => Dryer
            [email] => FredDryer1@email.com
            [d02] => Backfield
            [d03] => North
            [partnerid] => 14
        )

我可以通过在 $rowdata_tmp['d04'] = ''; 之前插入 d04 array_combine 语句,但问题是 d04 有时已经存在于 demos_keys.

有人可以帮忙吗?我快死在这里了。

您正在检查顶级 $rowdata 数组中的键,而不是您要添加到数组的新行。

$rowdata_tmp = explode(',', trim($row));
$rowdata_tmp[] = $partnerid;
$new_row = array_combine($demos_keys, $rowdata_tmp);
if (isset($new_row['d04'])) {
    $x = 1;
} else {
    $new_row['d04'] = '';
}
$rowdata[] = $new_row;