首页 > 解决方案 > PHP - 将值添加到已经存在的数组

问题描述

我有一个已经定义的数组,包含如下值:

$arr = ['a','b','c'];

如何使用 PHP 添加以下内容?

$arr = [
   'a' => 10,
   'b' => 5,
   'c' => 21
]

我试过了: $arr['a'] = 10但它抛出了错误:Undefined index: a

我肯定我犯了一个愚蠢的错误..有人可以睁开我的眼睛吗?

完整代码如下:

$finishes = []; //define array to hold finish types
foreach ($projectstages as $stage) {
    if ($stage->finish_type) {
        if(!in_array($stage->finish_type, $finishes)){
            array_push($finishes, $stage->finish_type); 
        }
    }
}

foreach ($projectunits as $unit) {
    $data[$i] = [
        'id' => $unit->id,
        'project_name' => $unit->project_name,
        'block_title' => $unit->block_title,
        'unit' => $unit->unit,
        'core' => $unit->core,
        'floor' => $unit->floor,
        'unit_type' => $unit->unit_type,
        'tenure_type' => $unit->tenure_type,
        'floors' => $unit->unit_floors,
        'weelchair' => $unit->weelchair,
        'dual_aspect' => $unit->dual_aspect
    ];  
    $st = array();    
    $bs = '';     
    foreach ($projectstages as $stage) {
        $projectmeasure = ProjectMeasure::select('measure')
                ->where('project_id',$this->projectId)
                ->where('build_stage_id', $stage->id)
                ->where('unit_id', $unit->id)
                ->where('block_id', $unit->block_id)
                ->where('build_stage_type_id', $stage->build_stage_type_id)
                ->first();

        $st += [
            'BST-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure : '0')
        ]; 
        
        if (($stage->is_square_meter == 0) && ($stage->is_draft == 0)) {
            $height = ($stage->height_override == 0 ? $unit->gross_floor_height : $stage->height_override); //08.14.20: override default height if build stage type has it's own custom height
            $st += [
                'BST-sqm-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure * $height: '0')
            ]; 
            if ($stage->finish_type) {
                $finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure * $height: '0') * ($stage->both_side ? 2 : 1); //error is thrown at this line
            }
        } else {
            if ($stage->finish_type) {
                $finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure : '0');
            }
        }

    }
    $data[$i] = array_merge($data[$i], $st);
    $data[$i] = array_merge($data[$i], $finishes[$stage->finish_type]);
    $i++;
}

上面的代码按原样使用,数组$finishes是第一个示例中的数组,称为$arr

标签: php

解决方案


+=在真实代码中使用而不是=. 这会尝试进行数学运算以添加到现有值,而=如果该值不存在,则可以使用该值分配一个新索引。

+=不能做数学来添加一个数字。您需要先检查索引是否存在。如果它不存在,则为其分配一个初始值。如果它已经存在一个值,那么您可以将新值添加到现有值。


推荐阅读