脚本宝典收集整理的这篇文章主要介绍了PHP合并具有相同键/值的数组,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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)
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) ]; } }
以上是脚本宝典为你收集整理的PHP合并具有相同键/值的数组全部内容,希望文章能够帮你解决PHP合并具有相同键/值的数组所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。