Php 将数组的数组与细节相似的值合并
假设我有一个数组:Php 将数组的数组与细节相似的值合并,php,Php,假设我有一个数组: $users = []; $users[0] = [ "Name" => "John Doe", "Age" => 48, "Email" => "john.doe@server-a.com", "Points" => 5 ]; $users[1] = [ "Name" => "John Brother", "Age" => 32, "Email" => "john.brot
$users = [];
$users[0] = [ "Name" => "John Doe", "Age" => 48,
"Email" => "john.doe@server-a.com", "Points" => 5 ];
$users[1] = [ "Name" => "John Brother", "Age" => 32,
"Email" => "john.brother@server-a.com", "Points" => 8 ];
$users[2] = [ "Name" => "John Doe", "Age" => 48,
"Email" => "john.doe@server-b.com", "Points" => 3 ];
$users[3] = [ "Name" => "John Doe", "Age" => 49,
"Email" => "john.doe@server-b.com", "Points" => 7 ];
在我的代码中,我需要在(相同的姓名+相同的年龄)或(相同的电子邮件)时合并用户,以汇总点数并返回此用户的唯一副本,同时考虑此用户的最新信息(如果合并)
因此,请注意:
可以与User#0
合并,因为它共享(同名+同龄)李>User#2
- 但是
不能直接与User#0
合并,因为它们没有相似性李>User#3
可以与User#2
合并,因为它共享(相同的电子邮件)李>User#3
- 因此,
可以间接地与User#0
和User#3
合并李>User#2
$users[] = [ "Name" => "John Brother", "Age" => 32,
"Email" => "john.brother@server-a.com", "Points" => 8 ];
$users[] = [ "Name" => "John Doe", "Age" => 49,
"Email" => "john.doe@server-b.com", "Points" => 15 ];
注意:合并后的
用户ID
无关紧要。我不确定是否有更有效或更优雅的方法,但您可以尝试以下方法:
$result = [];
$tmp = [];
array_walk($users, function ($value) use (&$result, &$tmp) {
$hash = md5($value['Name'].$value['Age']);
$sum = $value['Points'];
$e = $value['Email'];
if (array_key_exists($hash, $result)) {
$sum += $result[$hash]['Points'];
} elseif (array_key_exists($e, $tmp)) {
$hash = md5($tmp[$e]['Name'].$tmp[$e]['Age']);
$sum += $result[$hash]['Points'];
}
$result[$hash] = $tmp[$e] = $value;
$result[$hash]['Points'] = $sum;
});
$users = array_values($result);
var_dump($users);
输出为:
array (size=2)
0 =>
array (size=4)
'Name' => string 'John Doe' (length=8)
'Age' => int 49
'Email' => string 'john.doe@server-b.com' (length=21)
'Points' => int 15
1 =>
array (size=4)
'Name' => string 'John Brother' (length=12)
'Age' => int 32
'Email' => string 'john.brother@server-a.com' (length=25)
'Points' => int 8
你试图解决什么问题?