douzhushen_9776 2016-06-25 09:44
浏览 48
已采纳

使用php动态搜索jsonarray多个值

i have a json array

[  
  {  
     "id":1.25,
     "name":"rose",
     "Number":15,
     "SSN":[  
         12345,
         3455
     ]
  },

  {  
     "id":1.15,
     "name":"orchid",
     "Number":7,
     "SSN":[  
        12345,
        3455
     ]
  }
]

i want to get the id value if user searched with any ssn or name or by number.the input for search may not be single value that means it may be combination of ssn and name or it may be name,ssn and number .Any combination of name number ,ssn may be inputs .i have to get id value if the inputs matches using php .i used xpath for xml but i want to search fron json.can someone suggest me with any idea..thank you...

  • 写回答

3条回答 默认 最新

  • doukuang1950 2016-06-25 10:43
    关注

    To search user ID by analyzing JSON string use the following approach with array_filter and array_intersect_assoc functions:

    $json_str = '[ { "id":1.25, "name":"rose", "Number":15, "SSN":[ 12345, 3455 ] }, { "id":1.15, "name":"orchid", "Number":7, "SSN":[ 12345, 3455 ] }]';
    $decoded = json_decode($json_str, true);
    
    // base search structure
    $search_structure = ['name' => "", 'Number' => 0];
    
    // let's say, the following inputs have come from API (some of them may be empty or omitted)
    $number = 7;
    $ssn = "3455";
    
    if ($number && is_numeric($number)) $search_structure['Number'] = $number;
    $search_structure = array_filter($search_structure); // filtering out empty params
    $count_params = count($search_structure);
    $user_id = 0;
    
    foreach ($decoded as $item) {
        if ($count_params == count(array_intersect_assoc($search_structure, $item))) {
            if (!$ssn || ($ssn && in_array($ssn, $item['SSN']))) {
                $user_id = $item['id'];
                break;
            }
        }
    }
    
    print_r(($user_id)? "User id: $user_id" : "User with specified params not found!");
    

    The output:

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端