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

时间:2015-10-08 04:51:20

标签: php arrays sorting associative-array

我正在尝试在php中合并数组。一切都来自数据库,两个不同的结果可能如下所示:

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

使用array_merge()然后使用array_unique()应该给我这样的东西:

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

然后我如何按id_user值排序?我不确定理解不同的排序php函数......

3 个答案:

答案 0 :(得分:2)

您可以像{/ p>一样使用usort

usort($unique_and_merged_array,function($a,$b){
   return $a['id_user'] - $b['id_user'];
});
print_r($result);

<强>输出:

Array
(
    [0] => Array
        (
            [id_user] => 1
            [tokenId] => 123
        )

    [1] => Array
        (
            [id_user] => 2
            [tokenId] => 752
        )

    [2] => Array
        (
            [id_user] => 2
            [tokenId] => 456
        )

    [3] => Array
        (
            [id_user] => 3
            [tokenId] => 789
        )

    [4] => Array
        (
            [id_user] => 5
            [tokenId] => 789
        )

)

Demo

答案 1 :(得分:1)

基于PHP的解决方案可能如下所示:

//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 :(得分:1)

gets