很抱歉,我看到了多个类似的解决方案,但我无法在我的情况下实施它们。我试过检查是否在sum之前存在值,但是它给了我真正的值并且无法添加它的实际值。使用波纹管代码,只要循环运行并给出错误的总和值,它就会重复相同的值。请指正。
我想通过匹配键将数组值添加到单个数组中。
我有这个阵列......
Array(
[0] => Array
(
[Customer] => Array
(
[created_by] => 3
[amount] => 475
)
)
[1] => Array
(
[Customer] => Array
(
[created_by] => 5
[amount] => 199
)
)
[2] => Array
(
[Customer] => Array
(
[created_by] => 1
[amount] => 199
[refund_amount] => 200
[upgrade_amount] => 199
)
)
[3] => Array
(
[Customer] => Array
(
[created_by] => 1
[amount] => 199
)
)
[4] => Array
(
[Customer] => Array
(
[created_by] => 4
[upgrade_amount] => 199
)
)
) 我正在寻找像这样的结果......
Array(
[3] => Array
(
[sale] => 475
[refund] => 0
[upgrade] => 0
)
[5] => Array
(
[sale] => 199
[refund] => 0
[upgrade] => 0
)
[1] => Array
(
[sale] => 398
[refund] => 200
[upgrade] => 199
)
[4] => Array
(
[sale] => 0
[refund] => 0
[upgrade] => 199
)
)
我使用此代码获取结果....
foreach($records as $y_key => $y_value){
//print_r($y_value);
if(!isset($top_performer[$y_value['Customer']['created_by']])){
$top_performer[$y_value['Customer']['created_by']]['sale'] = 0;
$top_performer[$y_value['Customer']['created_by']]['refund'] = 0;
$top_performer[$y_value['Customer']['created_by']]['upgrade'] = 0;
}
$top_performer[$y_value['Customer']['created_by']]['sale']+= $y_value['Customer']['amount'];
$top_performer[$y_value['Customer']['created_by']]['refund']+= $y_value['Customer']['refund_amount'];
$top_performer[$y_value['Customer']['created_by']]['upgrade']+=$y_value['Customer']['upgrade_amount'];
}
答案 0 :(得分:0)
您的代码看起来不错,您只需要检查数组元素是否存在
foreach($records as $y_key => $y_value){
if(!isset($top_performer[$y_value['Customer']['created_by']])){
$top_performer[$y_value['Customer']['created_by']]['sale'] = 0;
$top_performer[$y_value['Customer']['created_by']]['refund'] = 0;
$top_performer[$y_value['Customer']['created_by']]['upgrade'] = 0;
}
$top_performer[$y_value['Customer']['created_by']]['sale'] += isset($y_value['Customer']['amount']) ? $y_value['Customer']['amount'] : 0;
$top_performer[$y_value['Customer']['created_by']]['refund'] += isset($y_value['Customer']['refund_amount']) ? $y_value['Customer']['refund_amount'] : 0;
$top_performer[$y_value['Customer']['created_by']]['upgrade'] += isset($y_value['Customer']['upgrade_amount']) ? $y_value['Customer']['upgrade_amount'] : 0;
}