Search code examples
jsonapigetjsonserverside-javascript

Fetch Images from json_decode()


My Api is returning Json data as

[[{"ID":"1","Image":"img01.jpg"}]]

I am fetching this data through api on local and trying to bind image but not able to do it . I have tried many solution here , but Seems I am missing something

$url = "http://getsjobs.esy.es/api.php?ID=1&format=json";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
    echo curl_error($ch);
}

curl_close($ch);
$data = json_decode($json,true);

//solution 1 
// for($i = 0; $i <= count($data); $i++) {
        // echo $data[$i][0];
        // echo $data[$i][Image];

    // }


//solution 2    
// foreach ($data  as $optie ) {
    // echo "name = " . $optie['Image'] . "<br>";

// }


//solution 3 
// foreach ($data as $key => $value)
              // {
          // echo $value[0];

           // }



//solution 4           
// foreach($json['Array']['Array'] as $item) {
    // print $item['Image'];

// }

//solution 4           
//echo $data->Array->Image;

I am Simplying Trying to fetch value 'img01.jpg' and want to tag to Img tag SRC .

Can anyone Please Tell What I am missing ? Any Hint will be Helpful


Solution

  • You have an array of arrays, and each has only one element, so it's impossible to guess which of the following is more appropriate. (If possible, get a response with more than one image to see what the structure of that JSON is like.)

    foreach ($data[0] as $item) {
      echo $item["Image"] . "\n"; // img01.jpg
    }
    
    foreach ($data as $item) {
      echo $item[0]["Image"] . "\n"; // img01.jpg
    }