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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?