Search code examples
phpunirest

Separate JSON response


I am getting a response using Unirest library, i need to separate the data, so that based on that data i can call my next query. Here is full json response i am getting while using Unirest library

echo '<pre>'; print_r($response->raw_body); echo '</pre>';

    {
  "status": "success",
  "images": [
    "http://www.example.com/12.jpg"
  ],
  "photos": [
    {
      "url": "http://www.example.com/12.jpg",
      "width": 205,
      "tags": [
        {
          "confidence": 0.978945010372561,
          "center": {
            "y": 64,
            "x": 129
          },
          "height": 79,
          "width": 79,
          "tid": "31337",
          "attributes": [
            {
              "smile_rating": 0.56,
              "smiling": true,
              "confidence": 0.56
            }
          ],
          "uids": [
            {
              "confidence": 0.35399999999999998,
              "prediction": "SE2",
              "uid": "SE2@SEA1"
            },
            {
              "confidence": 0.28999999999999998,
              "prediction": "SE1",
              "uid": "SE1@SEA1"
            },
            {
              "confidence": 0.16,
              "prediction": "Star1",
              "uid": "Star1@SEA1"
            },
            {
              "confidence": 0.106,
              "prediction": "SE3",
              "uid": "SE3@SEA1"
            },
            {
              "confidence": 0.037999999999999999,
              "prediction": "SE6",
              "uid": "SE6@SEA1"
            },
            {
              "confidence": 0.035000000000000003,
              "prediction": "SE5",
              "uid": "SE5@SEA1"
            },
            {
              "confidence": 0.017999999999999999,
              "prediction": "SE4",
              "uid": "SE4@SEA1"
            }
          ]
        }
      ],
      "height": 206
    }
  ]
}

What i am trying is to print like this

Confidence : 0.35399999999999998
Similar: Test2

Solution

  • Well, provided it is a valid JSON string, just use a simple json_decode() with true flag so that it returns an array. Example:

    $data = json_decode($response->raw_body, true);
    $i = 0;
    foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
        if($i == 5) break;
        echo 'Confidence: ' . $value['confidence'] . '<br/>';
        echo 'Similar: ' . $value['prediction'] . '<br/><br/>';
        $i++;
    }