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条)

报告相同问题?

悬赏问题

  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题