原代码:
foreach($result as $item){ $ret[$item['fid']]["{$time}_num"] = $item['num'] ?? 0; $ret[$item['fid']]["{$time}_money"] = $item['money'] ?? 0; $ret[$item['fid']]["{$time}_ml"] = $item['ml'] ?? 0;}
优化后的代码
$key_prefix = "{$time}_";
$ret[$item['fid']] = [ 'fid' => $item['fid'], $key_prefix . 'num' => $item['num'] ?? 0, $key_prefix . 'money' => $item['money'] ?? 0, $key_prefix . 'ml' => $item['ml'] ?? 0 ] + ($ret[$item['fid']] ?? []);
解释:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "blueberry", "c" => "cherry");$result = $array1 + $array2;
print_r($result);
输出:Array ( [a] => apple [b] => banana [c] => cherry )在上面的示例中,由于
$array1
数组中已经存在键名为b
的元素,所以$array2
中的b
元素被忽略,并且合并后的结果数组中只保留了键名为b
对应的值为banana
的元素。
来源地址:https://blog.csdn.net/wen854854321/article/details/130882380