使用php的对象数组中相同id的和
我想从两个对象数组中添加给定的_点,并在学生id的帮助下在单个对象数组中显示。在两个对象数组中,学生id是唯一的使用php的对象数组中相同id的和,php,Php,我想从两个对象数组中添加给定的_点,并在学生id的帮助下在单个对象数组中显示。在两个对象数组中,学生id是唯一的 Array ( [0] => stdClass Object ( [student_id] => 91 [given_points] => 8 [bonus_points] => 2 ) [1] => stdClass Object
Array
(
[0] => stdClass Object
(
[student_id] => 91
[given_points] => 8
[bonus_points] => 2
)
[1] => stdClass Object
(
[student_id] => 91
[given_points] => 6
[bonus_points] => 1
)
)
Array
(
[0] => stdClass Object
(
[student_id] => 95
[given_points] => 9
[bonus_points] => 1
)
[1] => stdClass Object
(
[student_id] => 95
[given_points] => 9
[bonus_points] => 1
)
)
由于这是一个stdClass数组,请使用->而不是括号
['']
还有另一种方法:(PHP>=5.5)
您可以尝试上面的代码。基本上,由于student_id是表的唯一标识符,并且您希望基于此实现逻辑,因此将其设置为新的数组键字段
上面的代码将处理尽可能多的记录,输出的数组如下所示:
Array
(
[91] => 16
[92] => 8
[93] => 8
)
添加了2个id为91的用户,其余用户是单独数组字段中的唯一用户。是否尝试循环数组?你能展示一下你试过的代码吗?预期结果是什么?$newarray=array();foreach($arr as$ar){foreach($ar as$k=>$v){if(array_key_存在($v,$newarray))$newarray[$v]['gived_points']=$newarray[$v]['gived_points']+$ar['gived_points'];else if($k==''student_id')$newarray[$v]=$ar;}}print_r($newarray);你能显示预期的输出吗?这些数组是分开的吗?@AmodKumar,如果你想对学生id和给定的分数求和,请检查我的答案。如果数组中有多个学生怎么办?你循环foreach,但用作for循环<代码>$array[$key][‘给定_点’]与
$value['gived_points']相同代码>上面的解决方案不起作用,请推荐其他东西在数组下有数组([0]=>stdClass对象([student\u id]=>91[奖励积分]=>8[奖励积分]=>2)[1]=>stdClass对象([student\u id]=>91[奖励积分]=>6[奖励积分]=>1)数组([0]=>stdClass对象([student\u id]=>95[奖励积分]=>9[奖励积分]=>1)[1]=>stdClass对象([student\u id]=>95[奖励积分]=>9[奖励积分]=>1]),对于student\u id=91,我必须显示为给定的_点的总和,对于student_id=95plz也一样检查上述问题并为sameHi推荐一些解决方案谢谢回复但上述代码不起作用plz推荐其他东西它不起作用,因为我使用数组作为示例,并且你有对象。只需像对象一样访问您的值,这只是一个微小的更改。
$sum_points = 0;
$sum_student_id=0;
foreach($array as $key=>$value){
if(isset($value->given_points))
$sum_points += $value->given_points;
if(isset($value->student_id))
$sum_student_id += $value->student_id;
}
echo $sum_points;
echo $sum_student_id;
$sum_points = array_sum(array_column($array, 'given_points'));
$sum_student_ids = array_sum(array_column($array, 'student_id'));
$array = [
0 => ['student_id' => 91,
'given_points' => 8,
'bonus_points' => 2
],
1 => ['student_id' => 91,
'given_points' => 8,
'bonus_points' => 2
],
2 => ['student_id' => 92,
'given_points' => 8,
'bonus_points' => 2
],
3 => ['student_id' => 93,
'given_points' => 8,
'bonus_points' => 2
]
];
foreach ($array as $row) {
if (isset($newArray[$row['student_id']])) {
$newArray[$row['student_id']] = $newArray[$row['student_id']] + $row['given_points'];
} else {
$newArray[$row['student_id']] = $row['given_points'];
}
}
print_r($newArray);
Array
(
[91] => 16
[92] => 8
[93] => 8
)