How to search through a JSON Array in PHP

前端 未结 3 2014
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 08:05

I have a JSON array

{
  \"people\":[
    {
      \"id\": \"8080\",
      \"content\": \"foo\"
    },
    { 
      \"id\": \"8097\",
      \"content\": \"ba         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-01 08:46

    Use the json_decode function to convert the JSON string to an array of object, then iterate through the array until the desired object is found:

    $str = '{
      "people":[
        {
          "id": "8080",
          "content": "foo"
        },
        { 
          "id": "8097",
          "content": "bar"
        }
      ]
    }';
    
    $json = json_decode($str);
    foreach ($json->people as $item) {
        if ($item->id == "8097") {
            echo $item->content;
        }
    }
    

提交回复
热议问题