php - 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
解决方案
您+=
在真实代码中使用而不是=
. 这会尝试进行数学运算以添加到现有值,而=
如果该值不存在,则可以使用该值分配一个新索引。
+=
不能做数学来添加一个数字。您需要先检查索引是否存在。如果它不存在,则为其分配一个初始值。如果它已经存在一个值,那么您可以将新值添加到现有值。
推荐阅读
- jquery - 使侧边栏在页面滚动时保持粘性
- nvd3.js - 如何在非丑陋模式下在 X 轴上绘制时间?
- javascript - 与多个 where 条件一起使用时,Firebase Firestore OrderBy 不起作用
- omnet++ - 模块 LteMacEndRealisticD2D 中的错误:out_of_range 向量
- c# - 从 C# 对 RPG 程序的调用是否同步?
- php - PHP 避免重复相同的 try catch
- node.js - 排序在 mongoDB 和 Nodejs 中不起作用
- r - 如何在r中将多个Hexbin图排列在一起?
- java - 消费者期待 List 的回应
使用协议 - perl - 将逗号分隔的值转换为键值对 Perl