dtmu88600 2014-06-18 17:53
浏览 32
已采纳

PHP - 检测嵌套数组中的重复值

I'm using an API which returns some JSON that I output in PHP.

PHP

$result = $api->sendRequest("getUsers", $inputParameters);
$output = json_decode($result, true);

An example of an array returned by the API. I can print out specific field values fine, but I can't figure out how to write a simple if statement that indicates whether or not there are duplicate names within the query result, specifically duplicate [fullName] fields as seen below.

Array
(
    [status] => Array
        (
            [request] => getUsers
            [recordsTotal] => 3
            [recordsInResponse] => 3
        )

    [records] => Array
        (
            [0] => Array
                (
                    [fullName] => Smith, Tom
                    [firstName] => Tom
                    [lastName] => Smith

                )

            [1] => Array
                (
                    [fullName] => Jones, Bill
                    [firstName] => Bill
                    [lastName] => Jones
                )

            [2] => Array
                (
                    [fullName] => Smith, Tom
                    [firstName] => Tom
                    [lastName] => Smith
                )

        )

)

Any help would be greatly appreciated.

  • 写回答

4条回答 默认 最新

  • dongwu1992 2014-06-18 18:07
    关注

    Not tested, but maybe try something like

    function dupeCheck($array, $attribute = 'fullName') {
        $list = array();
        foreach($array['records'] as $value) {
            if(in_array($value[$attribute], $list))
                return true;
            $list[] = $value[$attribute];
        }
        return false;
    }
    

    Just iterating over the records, we maintain a list of values of whatever attribute, once it finds one that was already in the array, returns true.

    Then just:

    if(!dupeCheck($output, 'fullName')) { // no dupes in the API response }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源