dougua9165 2015-10-08 04:51
浏览 62
已采纳

合并,删除重复项并在php中排序关联数组

I am trying to merge arrays in php. Everything is coming from a database and two different results could look like this:

array[0]['id_user'] = 1
array[0]['tokenId'] = 123
array[1]['id_user'] = 2
array[1]['tokenId'] = 456
array[2]['id_user'] = 5
array[2]['tokenId'] = 789

array[0]['id_user'] = 1
array[0]['tokenId'] = 123
array[1]['id_user'] = 2
array[1]['tokenId'] = 752
array[2]['id_user'] = 3
array[2]['tokenId'] = 789

Using array_merge() and then array_unique() should give me something like this I expect:

unique_and_merged_array[0]['id_user'] = 1
unique_and_merged_array[0]['tokenId'] = 123
unique_and_merged_array[1]['id_user'] = 2
unique_and_merged_array[1]['tokenId'] = 456
unique_and_merged_array[2]['id_user'] = 5
unique_and_merged_array[2]['tokenId'] = 789
unique_and_merged_array[3]['id_user'] = 2
unique_and_merged_array[3]['tokenId'] = 752
unique_and_merged_array[4]['id_user'] = 3
unique_and_merged_array[4]['tokenId'] = 789

Then how can I sort by id_user value? I'm not sure to understand the different sorting php functions ...

  • 写回答

3条回答 默认 最新

  • douya7282 2015-10-08 05:35
    关注

    The PHP-based solution could look something like this:

    //Define arrays for testing
    $array1[0]['id_user'] = 1;
    $array1[0]['tokenId'] = 123;
    $array1[1]['id_user'] = 2;
    $array1[1]['tokenId'] = 456;
    $array1[2]['id_user'] = 5;
    $array1[2]['tokenId'] = 789;
    
    $array2[0]['id_user'] = 1;
    $array2[0]['tokenId'] = 123;
    $array2[1]['id_user'] = 2;
    $array2[1]['tokenId'] = 752;
    $array2[2]['id_user'] = 3;
    $array2[2]['tokenId'] = 789;
    
    //Define sort function - compares arrays using the 'id_user' value
    function sortByUserId($array1, $array2)
    {
        if ($array1['id_user'] == $array2['id_user']) {
            return 0;
        }
        return ($array1['id_user'] < $array2['id_user']) ? -1 : 1;
    }
    
    //Merge arrays
    $unique_and_merged_array = array_merge($array1, $array2);
    
    //Remove duplicate entries - note SORT_REGULAR in order to work with multidimensional arrays
    $unique_and_merged_array = array_unique($unique_and_merged_array, SORT_REGULAR);
    
    //Sort the arrays
    uasort($unique_and_merged_array, 'sortByUserId');
    
    //Enjoy  ;)
    var_dump($unique_and_merged_array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档