[英]Fast way to remove duplicates by id from a PHP array
I have an array and would like to remove duplicates. 我有一个数组,想删除重复项。 I'm using php. 我正在使用php。 How to remove duplicate rows (by id). 如何删除重复的行(按ID)。
My array looks like: 我的数组看起来像:
Array
(
[0] => Array
(
[id] => 415
)
[1] => Array
(
[id] => 425
)
[2] => Array
(
[id] => 425
)
[3] => Array
(
[id] => 426
)
)
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. 假设id
是数组的唯一元素,则可以使用serialize
和array_unique
浏览整个数组,因为array_unique
本身不适用于多维数组。
$foo = array_map('unserialize', array_unique(array_map("serialize", $foo)));
If you have other elements, @Ghost's answer is probably better 如果您还有其他元素,@ Ghost的答案可能更好
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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.