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 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用