0

I have the below valid JSON that has the key best_images that is causing my problems.

$json_array =  {
 "best_images": 
     [{
        "id": "1",
        "Title": "My Image 1",
        "Photographer": "Kate Doe",
        "Album": "Album 1",
        "Imagefilename": "image1.jpg",
        "Year": "2005",
        "Size": "1.91 MB"

    },
    {
        "id": "2",
        "Title": "My Image 2",
        "Photographer": "Jermaine Kavme",
        "Album": "Album 2",
        "Imagefilename": "image2.jpg",
        "Year": "2012",
        "Size": "5.13 MB"

    },
    {
        "id": "4",
        "Title": "My Image 4",
        "Photographer": "Kate Doe2",
        "Album": "Album 4",
        "Imagefilename": "image4.jpg",
        "Year": "2012",
        "Size": "1.31 MB"

    }
    ]
}

I want to decode it, and I am using the following method:

$obj = json_decode($json_string, true); however, when I use the below code to get the keys, I am getting one the best_images key and not the rest.

foreach ($obj as $key => $value) 
{     
echo $key;    
}

How can I get the deeper than the first big key (what is it called actually) to reach the below keys?

Also, how can I separate each inner object so that I can put each one in database row?

1
  • Nested foreach loops Commented Jun 2, 2017 at 8:29

2 Answers 2

4

Use this as you know the 1st array key is "best_image":

foreach ($obj["best_image"] as $key => $value) 
{     
  echo $key;    
}

Otherwise you need to loop it twice.

 foreach ($obj["best_image"] as $mainkey => $arrObj) 
     foreach ($arrObj as $key => $value) 
     {     
       echo $key;   
     } 
 }
}
Sign up to request clarification or add additional context in comments.

2 Comments

don't forget an if (isset($obj['best_image'])) condition :p if it's an API you may never know what comes in :O
I will suggest you check !empty() check before each foreach()
2

Use a recursive function:

function show_arr_r($arr, $level=0)
{
   foreach ($arr as $k=>$v) {
      for ($x=0; $x<$level $x++) print '.';
      print "$k="; 
      if (is_array($v)) {
         print "\n";
         show_arr($k, $level+1);
      } else {
         print $k . "\n";
      }
   }
 }

Or use print_r, or var_export.

But usually you want to do something with the data - you reference deeper array elements simply by adding more []:

if ($obj["best_images"][1]["Photographer"]=="Kate Doe") {

Or...

if ($obj->best_images[1]->Photographer=="Kate Doe") {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.