我想这样做:
foreach($values as $key => $value){
//modify the key here, so it could be the same as one before
//group by key and accumulate values
$data[$key]['total'] += $value - $someothervalue;
}
在php中是可能的吗?还是我总是要先检查这个?
isset($data[$key]['total'])
如果我理解正确的话,你可以不检查是否只在php7及以上版本中存在
foreach($values as $key => $value)
$data[$key]['total'] = ($data[$key]['total'] ?? 0) + $value - $someothervalue;;
无论如何PHP允许你创建这样的新键,但不要忘记在你的服务器中禁用错误报告,以避免通知…
Php允许将NULL
值添加到数字(当用于数字操作+,-,*
时将其处理为0),因此如果您不介意覆盖它(并且从+=
操作符我认为您不介意),则不需要检查isset($data[$key]['total'])
。
您可以使用+=
增加一个不存在的键。如果它不存在,PHP将自动创建它,初始值为null
,当您尝试添加它时,它将被强制转换为零。这将在每次发生时生成两个通知:
注意:未定义offset: x
其中x
为$key
和
注意:未定义索引:total
如果你不在乎这些通知,那就去吧。它会成功的。如果您确实关心这些通知,则必须在对其进行任何操作之前检查该键是否存在。正如您所说的isset($data[$key]['total'])
将为此工作,但实际上您只需要检查isset($data[$key])
,因为您只为每个$key
写入'total'
。
foreach($values as $key => $value){
//modify the key here, so it could be the same as one before
//group by key and accumulate values
$inc = $value - $someothervalue;
if (isset($data[$key])) {
$data[$key]['total'] += $inc;
} else {
$data[$key]['total'] = $inc;
}
}
我建议这样做,因为我确实关心通知。还有很多其他的问题在讨论这个问题。
谢谢大家的回答。我选了:
foreach($values as $key => $value){
//modify the key here, so it could be the same as one before
//group by key and accumulate values
$inc = $value - $someothervalue;
if (!isset($data[$key]['total']){
$data[$key]['total'] = 0;
}
$data[$key]['total'] = += $inc;
}