Search code examples
phpjsonarray-filter

Search in array in json file


I have an array which has a key with multiple content. I want to get that array which includes the key that I search .

$arr = json_decode('{"people":[
{
  "id": "8080",
  "content": "foo",
  "member": [123, 456],
  "interval": 7
},
{ 
  "id": "8097",
  "content": "bar",
  "member": [1234, 4567],
  "interval": 7
}


]}', true);


$results = array_filter($arr['people'], function($people) {
    return $people['id'] == 8080;
});

echo json_encode($results);

This will return:

{"id":"8080","content":"foo","member":[123,456],"interval":7}

I want that:

$results = array_filter($arr['people'], function($people) {
    return $people['member'] == 123;
});

And this does not work.

Have somebody an idea?


Solution

  • As @JonStirling said in comment. Use in_array() function.

    $arr = json_decode('{"people":[
    {
      "id": "8080",
      "content": "foo",
      "member": [123, 456],
      "interval": 7
    },
    { 
      "id": "8097",
      "content": "bar",
      "member": [1234, 4567],
      "interval": 7
    }
    
    
    ]}', true);
    
    $searchId = 123;
    $results = array_filter($arr['people'], function($people) use ($searchId) {
        return in_array($searchId, $people['member']);
    });
    
    echo json_encode($results);
    

    Result:

    [{"id":"8080","content":"foo","member":[123,456],"interval":7}]