douhao2856 2014-10-17 10:02
浏览 54
已采纳

再一次关于从PHP中的多维数组中删除重复值

After an exhausting search I found some similar problems like the one I would like to solve, but I could not use their answers.

Hier are some very good examples:

How to remove duplicate values from a multi-dimensional array in PHP

How to remove duplicate values from a multi-dimensional array in PHP

How to remove duplicate values from a multi-dimensional array in PHP revisited

This one is the most similar, but the answer somehow doesn't work to me.

php filter array values and remove duplicates from multi dimensional array

The main difference to my issue is that while people are looking for a solution to delete an entire duplicated subarray from the array, I'm trying to delete the subarray when only one $key => $value pair of the subarray is similar to the correspondent pair of another subarray. The other pairs could have different values or even the same.

Here my array:

Array(

[0] => Array
    (
        [0] => AAA
        [1] => 500
    )

[1] => Array //Won't be delete 'cause [0] is different, although [1] is the same.
    (
        [0] => BBB
        [1] => 500
    )

[2] => Array //Will be delete 'cause [0] is the same.
    (
        [0] => AAA
        [1] => 500
    )

[3] => Array //Won't be delete 'cause [0] is different.
    (
        [0] => CCC
        [1] => 820
    )

[4] => Array
    (
        [0] => AAA //Will be delete 'cause [0] is the same. [1] is also different.
        [1] => 774
    )

How could I manage to delete these subarrays so I have following result:

Array(

[0] => Array
    (
        [0] => AAA
        [1] => 500
    )

[1] => Array
    (
        [0] => BBB
        [1] => 500
    )

[2] => Array
    (
        [0] => CCC
        [1] => 820
    )

Many thanks in advance!

  • 写回答

2条回答 默认 最新

  • duai4379 2014-10-17 10:07
    关注

    The easiest solution (in my opinion), instead of using magical array_filter and array_map handicraft which is difficult to maintain, is to write a specialized function yourself:

    $out = [];
    $usedKeys = [];
    foreach ($in as $element)
    {
        list ($a, $b) = $element;
        if (!isset($usedKeys[$a]))
        {
            $usedKeys[$a] = true;
            $out[]= $element;
        }
    }
    var_dump($out);
    

    This will return only elements whose first pair element is unique (taking first one, if multiple entries are available).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?