简体   繁体   English

使用php动态搜索jsonarray以获取多个值

[英]Search jsonarray for multiple values dynamically using php

i have a json array 我有一个json数组

[  
  {  
     "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... 如果用户使用任何ssn或name或number搜索,我想获取id值。搜索的输入可能不是单个值,这意味着它可能是ssn和name的组合,也可能是name,ssn和number的任何组合。名称编号,ssn可能是输入。如果输入使用php匹配,我必须获得id值。我使用xpath作为xml,但是我想搜索json。有人可以建议我有什么想法..谢谢...

To search user ID by analyzing JSON string use the following approach with array_filter and array_intersect_assoc functions: 通过分析JSON字符串中使用下列方法处理搜索用户ID array_filterarray_intersect_assoc功能:

$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

Lets $json contains an array string 让$ json包含一个数组字符串

$ar = json_decode($json, true);
$id = false;
foreach ($ar as $i) 
   if ($i["name"] == "rose" and  $i["Number"] == 15)
      { $id = $i["id"]; break; }
if ($id !== false) { 
   // use $id
}

Preferably, convert the json data to native PHP Object and then using foreach, loop over the object and extracting the ID of the Objects that match the given SSN Number. 最好convert the json data to native PHP Object ,然后使用foreach遍历该对象并提取与给定SSN编号匹配的对象ID。 The result of the extraction would be assigned to an array. 提取结果将分配给数组。 Below is a Commented procedure of 1 possible way of going about this: 以下是进行此操作的一种可能方法的注释过程:

    <?php

        // WE ASSUME, JUST FOR TESTING PURPOSES THAT THE SSN NUMBER WE ARE LOOKING FOR IS 4567
        $ssnNumber  = 4567; //3455;

        // CREATE A NEW ARRAY VARIABLE TO HOLD THE IDs YOU DESIRE & INITIALIZE IT TO AN EMPTY ARRAY
        $arrIDS     = array();
        $jsonData   = '[
              {
                 "id"       :1.25,
                 "name"     :"rose",
                 "Number"   :15,
                 "SSN"      :[
                        12345,
                        3455
                 ]
              },

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

              {
                 "id"       :1.75,
                 "name"     :"orchid",
                 "Number"   :79,
                 "SSN"      :[
                        4567,
                        89012
                 ]
              }
            ]';
        // CONVERT $jsonData TO NATIVE PHP OBJECT
        $objJson    = json_decode($jsonData);

        // LOOP THROUGH THE PHP OBJECT & TEST IF A GIVEN SSN EXIST.
        foreach($objJson as $key=>$data){
            // CHECK IF THE $data->SSN IS SET:
            if(isset($data->SSN) && is_array($data->SSN)){
                // CHECK IF THE SSN ARRAY CONTAINS THE GIVEN SSN NUMBER.
                if(in_array($ssnNumber, $data->SSN)){
                    $arrIDS[]   = $data->id;
                }
            }
        }
        var_dump($arrIDS);  // DISPLAY: array (size=1) 0 => float 1.75

Alternatively, one could as well encapsulate the above Routine withina Function for re-usability like so: 或者,也可以封装上述例行程序withina函数以实现可重用性,如下所示:

    <?php    
        function getIDBySSN($jsonData, $ssnNumber){
            $arrIDs     = array();
            $objJson    = json_decode($jsonData);
            // LOOP THROUGH THE PHP OBJECT & TEST IF A GIVEN SSN EXIST.
            foreach($objJson as $key=>$data){
                // CHECK IF THE $data->SSN IS SET:
                if(isset($data->SSN) && is_array($data->SSN)){
                    // CHECK IF THE SSN ARRAY CONTAINS THE GIVEN SSN NUMBER.
                    if(in_array($ssnNumber, $data->SSN)){
                        $arrIDs[]   = $data->id;
                    }
                }
            }
            return $arrIDs;
        }

        var_dump(getIDBySSN($jsonData, $ssnNumber)); // PRODUCES THE SAME RESULT

Test it HERE: 这里测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM