从PHP数组中通过id删除重复项的快速方法
问题描述:
I have an array and would like to remove duplicates. I'm using php. How to remove duplicate rows (by id).
My array looks like:
Array
(
[0] => Array
(
[id] => 415
)
[1] => Array
(
[id] => 425
)
[2] => Array
(
[id] => 425
)
[3] => Array
(
[id] => 426
)
)
我有一个数组,想要删除重复项。 我正在使用php。 如何删除重复的行(通过id)。
我的数组如下所示: p>
Array
(
[0] => Array
(\ n [id] => 415
)
[1] =>数组
(
[id] => 425
)
[2] =>数组
(
[ id] => 425
)
[3] =>数组
(
[id] => 426
)
)
code> pre>
DIV>
答
Assuming that id
is the only element of the array, you can walk through the array using serialize
and array_unique
, as array_unique
by itself doesn't work with multidimensional arrays.
$foo = array_map('unserialize', array_unique(array_map("serialize", $foo)));
If you have other elements, @Ghost's answer is probably better
答
This will also flatten the array to a 1-dimensional array
$data = array(
array(
'id' => 415,
),
array(
'id' => 425,
),
array(
'id' => 425,
),
array(
'id' => 426,
),
);
$data = array_unique(
array_map('end', $data)
);
var_dump($data);
gives
Array
(
[0] => 415
[1] => 425
[3] => 426
)