douke8473 2017-03-21 07:04
浏览 38
已采纳

在json文件中搜索数组

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

  1. $arr = json_decode('{"people":[
  2. {
  3. "id": "8080",
  4. "content": "foo",
  5. "member": [123, 456],
  6. "interval": 7
  7. },
  8. {
  9. "id": "8097",
  10. "content": "bar",
  11. "member": [1234, 4567],
  12. "interval": 7
  13. }
  14. ]}', true);
  15. $results = array_filter($arr['people'], function($people) {
  16. return $people['id'] == 8080;
  17. });
  18. echo json_encode($results);

This will return:

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

I want that:

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

And this does not work.

Have somebody an idea?

展开全部

  • 写回答

3条回答 默认 最新

  • dongpu3792 2017-03-21 07:37
    关注

    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}]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部