0

So, im trying to display the images that are in my JSON file on my website by calling the json file into my php but i get this notice "Array to string conversion". Any ideas on how i should solve this problem?

JSON

[
{
"name" : "match numbers 1",
"template" : "matching",
"data" : [
  [
   "one",
   "Images/Number1.jpg"
  ],
  [
   "four",
   "Images/Number4.jpg"
  ],
  [
   "nine",
   "Images/Number9.jpg"
  ]
]
},

{
"name" : "match numbers 2",
"template" : "matching",
"data" : [
  [
   "six",
   "Images/Number6.jpg"
  ],
  [
   "eight",
   "Images/Number8.jpg"
  ],
  [
   "nine",
   "Images/Number9.jpg"
  ]
]
  }
]

php code

<?php
  $json_var = file_get_contents("template.json");
  $json_var = json_decode($json_var, true);
  foreach($json_var as $value)
  {
    printf($value["name"]);
    printf($value["template"]);
    printf('<img src="'.$value["data"].'" />');
  }
?>

2 Answers2

2

because $value["data"] is array so you can iterate and get all images

<?php
  $json_var = file_get_contents("template.json");
  $json_var = json_decode($json_var, true);
  foreach($json_var as $value)
  {
    printf($value["name"]);
    printf($value["template"]);
    foreach($value["data"] as $val){
     printf('<img src="'.$val[1].'" />'); //$val is also array, i assumed second is image url 
    }
  }
?>
suresh bambhaniya
  • 1,687
  • 1
  • 10
  • 20
0

The "Array to string conversion" error is happening because your $value["data"] is an array. You will also want to iterate through that array as well. Something like this.

<?php
  $json_var = file_get_contents("template.json");
  $json_var = json_decode($json_var, true);
  foreach($json_var as $value)
  {
    printf($value["name"]);
    printf($value["template"]);
    foreach($value["data"] as $data){
     printf('<img src="'.$data[1].'" />'); //<- I assume this index
    }
  }
?>

Whenever I see the pesky Array to string conversion. var_dump is my best friend to debug the formatting.