PHP 数组去除重复并且记录值
$arr
=
array
(
array
(
'user_id'
=> 100,
'goods_id'
=> 10,
'number'
=> 1,
),
array
(
'user_id'
=> 102,
'goods_id'
=> 10,
'number'
=> 1,
),
array
(
'user_id'
=> 102,
'goods_id'
=> 10,
'number'
=> 1,
),
array
(
'user_id'
=> 102,
'goods_id'
=> 10,
'number'
=> 1,
),
);
$container
=
array
();
$result
=
array
();
foreach
(
$arr
as
$item
) {
$key
=
$item
[
'user_id'
] .
'_'
.
$item
[
'goods_id'
];
if
(
empty
(
$container
[
$key
])) {
$container
[
$key
] =
$item
[
'number'
];
}
else
{
$container
[
$key
] +=
$item
[
'number'
];
}
}
foreach
(
$container
as
$key
=>
$item
) {
list(
$user_id
,
$goods_id
) =
explode
(
'_'
,
$key
);
$result
[] =
array
(
'user_id'
=>
$user_id
,
'goods_id'
=>
$goods_id
,
'number'
=>
$item
);
}
运行结果
array (
0 =>
array (
'user_id' => '100',
'goods_id' => '10',
'number' => 1,
),
1 =>
array (
'user_id' => '102',
'goods_id' => '10',
'number' => 3,
),
)
一个平凡的少年,不愿随大流,选择了编程之路。