1

I've been trying to mess around with some JSON data for an idea that I have, but when I try to foreach loop through the JSON, it's only returns the first character for all the data and not just the first_name in my test.

Code

<?php
  $jsondata ='{"first_name":"John","last_name":"Doe","guest_link":"test test","id":"3"}';
  $json = json_decode($jsondata, true);
  ?>
  <?php foreach($json as $item) : ?>
    <p>
      <?php echo $item['first_name']; ?>
    </p>
  <?php endforeach; ?>

Result

J

D

t

3

If I do a var_dump this is what I get:

string(4) "John"
string(3) "Doe"
string(9) "test test"
string(1) "3"

So, I'm not sure if I'm missing something, or if I'm just going about this the wrong way.

1 Answer 1

3

Your JSON string has only one object, without nested objects or arrays.

So you have to try in this way:

$json = json_decode($jsondata, true);
echo $json['first_name'];

or in this way:

$json = json_decode($jsondata, true);
foreach( $json as $key => $item )
{
    echo $item;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Ahhhhh, ok. So, I don't "technically" need the foreach loop. I can just call in the data outright with echo. Man, I thought I would have to use a foreach loop for the data.
And if you dont convert the OBJECT to and Array you can simple use $json->first_name and $json->last_name etc
I have this exact problem but my application will scale to require the foreach... does someone have an actual explanation as to why the above code does not work?
So the solution I found was that I had to alter my json serialization to put my array of key:value pairs into a larger array. Then everything worked as it was supposed to.

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.