Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将数组的数组与细节相似的值合并_Php - Fatal编程技术网

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

你试图解决什么问题?