PHP 数组去除重复平且记录值
Posted 小强君
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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,
),
)
以上是关于PHP 数组去除重复平且记录值的主要内容,如果未能解决你的问题,请参考以下文章