0

I'm working with some JSON data like this:

    {
  "attachments": [
    {
      "content": "<base 64 encoded attachment>", 
      "content_type": "image/jpeg", 
      "original_name": "image000000.jpg"
    }, 
    {
      "content": "<base 64 encoded attachment>", 
      "content_type": "image/gif", 
      "original_name": "gif0001.jpg"
    }
  ], 
  "source_number": "++614567890"
}

I need to loop through all the attachments array. I can get individual elements like this:

$arr = json_decode($jsonobj, true);
echo $arr[attachments][0]["content_type"]; // returns image/jpeg

but I can't work out the syntax to loop through all of the attachments array and retrieve the values for each of these, something like this pseudo code:

    foreach($arr[attachments] as $key => $value) {
  $contentType = $arr[attachments][0]["content_type" ;
  $content = $arr[attachments][0]["content" ;
  $originalName = $arr[attachments][0]["original_name" ;
}

that will generate a variable in the loop for each item in the attachments array.

2 Answers 2

1

You don't need the $key, you just need the $value. In the loop, $value is associative array that has the keys content, content_type and original_name:

foreach($arr["attachments"] as $value) {
  $contentType = $value["content_type"];
  $content = $value["content"];
  $originalName = $value["original_name"];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are almost there: $value['content_type'] (and so on) inside your loop will do the trick. (The $key is superfluous.)

Oh and you should use $arr['attachments'] instead of $arr[attachments] probably.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.