PHP过滤数组值,并从多维数组中删除重复项 [英] php filter array values and remove duplicates from multi dimensional array

查看:93
本文介绍了PHP过滤数组值,并从多维数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我试图从此数组中查找重复的x值并将其删除,只保留唯一的x值.例如我的数组是

Hello all im trying to find duplicate x values from this array and remove them and only leave the unique ones. For example my array is

Array
(
[0] => Array
    (
        [x] => 0.5
        [y] => 23
    )

[1] => Array
    (
        [x] => 23
        [y] => 21.75
    )

[2] => Array
    (
        [x] => 14.25
        [y] => 21.875
    )

[3] => Array
    (
        [x] => 19.375
        [y] => 21.75
    )

[4] => Array
    (
        [x] => 9.125
        [y] => 21.875
    )

[5] => Array
    (
        [x] => 23
        [y] => 19.625
    )

[6] => Array
    (
        [x] => 19.375
        [y] => 19.625
    ) 
)

所以我需要做的是遍历整个事物,然后将第一个x值看成.5,然后继续,其他任何将x设为.5的东西都从数组中删除,这样最后我就有了一个看起来像数组的数组像这样

So what i need to happen is loops through the entire thing and see the first x value as .5 then continue and whatever else has x as .5 remove it from the array so that at the end i have a array that looks like this

 Array
   (
[0] => Array
    (
        [x] => 0.5
        [y] => 23
    )

[1] => Array
    (
        [x] => 23
        [y] => 21.75
    )

[2] => Array
    (
        [x] => 14.25
        [y] => 21.875
    )

[3] => Array
    (
        [x] => 19.375
        [y] => 21.75
    )

[4] => Array
    (
        [x] => 9.125
        [y] => 21.875
    )
)

,其中所有X值都是唯一的.我在线搜索,发现要使用此功能,但这似乎不起作用:

where all the X values are unique. I searched online and found this function to use but this doesnt seem to work:

 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));    

推荐答案

只需遍历并查找唯一的值即可:

Just loop through and find unique values as you go:

$taken = array();

foreach($items as $key => $item) {
    if(!in_array($item['x'], $taken)) {
        $taken[] = $item['x'];
    } else {
        unset($items[$key]);
    }
}

第一次使用x值时,我们将其保存-后续用法是数组中的unset.

Each the first time the x value is used, we save it - and subsequent usages are unset from the array.

这篇关于PHP过滤数组值,并从多维数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆