PHP合并具有相同键/值的数组
发布时间:2020-12-13 21:33:36 所属栏目:PHP教程 来源:网络整理
导读:如果我希望将这个 PHP数组合并为一个数组中的最低ID(1649).所以我只会看到 array:1 [ 1649 = array:2 [ "firstName" = "jack" "lastName" = "straw" "mergedWith" array:3 [ "id" ='1650' "id" ='1651' "id" ='1652' ] ] ] 而不是…… array:4 [ 1649 = arra
如果我希望将这个
PHP数组合并为一个数组中的最低ID(1649).所以我只会看到
array:1 [ 1649 => array:2 [ "firstName" => "jack" "lastName" => "straw" "mergedWith" array:3 [ "id" =>'1650' "id" =>'1651' "id" =>'1652' ] ] ] 而不是…… array:4 [ 1649 => array:2 [ "firstName" => "jack" "lastName" => "straw" ] 1650 => array:2 [ "firstName" => "jack" "lastName" => "straw" ] 1651 => array:2 [ "firstName" => "jack" "lastName" => "straw" ] 1652 => array:2 [ "firstName" => "jack" "lastName" => "straw" ] ] 我有一个循环运行,可以拉出重复项并找到组中的最低ID,但不确定将它们合并为一个的正确方法. 我展示的代码是搜索结果,该搜索已在这些特定字段中标识了具有重复条目的ID.我只是想进一步细化它不删除,但在id 1649的末尾添加一个字段,表示mergedWith(1650,1651,1652) 解决方法
一种方法是按名字和姓氏分组,然后反转分组以获得单个ID.事先kursort输入,以确保您获得最低的ID.
krsort($input); //group foreach ($input as $id => $person) { // overwrite the id each time,but since the input is sorted by id in descending order,// the last one will be the lowest id $names[$person['lastName']][$person['firstName']] = $id; } // ungroup to get the result foreach ($names as $lastName => $firstNames) { foreach ($firstNames as $firstName => $id) { $result[$id] = ['firstName' => $firstName,'lastName' => $lastName]; } } 编辑:根据您更新的问题,没有太多不同.只保留所有ID而不是单个ID. krsort($input); foreach ($input as $id => $person) { // append instead of overwrite ↓ $names[$person['lastName']][$person['firstName']][] = $id; } foreach ($names as $lastName => $firstNames) { foreach ($firstNames as $firstName => $ids) { // $ids is already in descending order based on the initial krsort $id = array_pop($ids); // removes the last (lowest) id and returns it $result[$id] = [ 'firstName' => $firstName,'lastName' => $lastName,'merged_with' => implode(',',$ids) ]; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |