php二维数组转成一维数组并且去重

原始二维数组数据:

$array = [
    [
        ["user_id"=>1,"username"=>"elgo"],
        ["user_id"=>2,"username"=>"el"],
        ["user_id"=>3,"username"=>"go"]
    ],
    [
        ["user_id"=>1,"username"=>"elgo"],
        ["user_id"=>2,"username"=>"el"],
        ["user_id"=>3,"username"=>"go"],
        ["user_id"=>10,"username"=>"hello"],
        ["user_id"=>20,"username"=>"word"]
    ]
];

需要将二维数组转成一维数组,并且去掉重复数据

  • 将数组转成一维数组
$result = array_merge(...$array);
print_r($result);

# 输入结果:
> Array
(
    [0] => Array
        (
            [user_id] => 1
            [username] => elgo
        )
    [1] => Array
        (
            [user_id] => 2
            [username] => el
        )
    [2] => Array
        (
            [user_id] => 3
            [username] => go
        )
    [3] => Array
        (
            [user_id] => 1
            [username] => elgo
        )
    [4] => Array
        (
            [user_id] => 2
            [username] => el
        )
    [5] => Array
        (
            [user_id] => 3
            [username] => go
        )
    [6] => Array
        (
            [user_id] => 10
            [username] => hello
        )
    [7] => Array
        (
            [user_id] => 20
            [username] => word
        )
)

array_merge 函数将多个数组进行合并

... 语法,简单点理解就是将数组展开,点击查看...语法

  • 去除数组中重复数据
$result= array_unique($result,SORT_REGULAR);
print_r($result)

# 输出结果:
> Array
(
    [0] => Array
        (
            [user_id] => 1
            [username] => elgo
        )
    [1] => Array
        (
            [user_id] => 2
            [username] => el
        )
    [2] => Array
        (
            [user_id] => 3
            [username] => go
        )
    [6] => Array
        (
            [user_id] => 10
            [username] => hello
        )
    [7] => Array
        (
            [user_id] => 20
            [username] => word
        )
)

你可能感兴趣的:(php二维数组转成一维数组并且去重)