1

Trying to learn JSON. Doing some simple exercises, but can't get past this one. I've rewatched the tutorial about 30 times. Any pointers?

here's the JSON:

{
  "name": "Username",
  "profile_name": "profile_username",
  "profile_url": "http://myapi.net/profile_username"
  "courses": [
    { "name": "English 340" },
    { "name": "History 202" },
    { "name": "Underwater Basket Weaving" }
  ]
}

It's in a variable called $JSON_array, and here's the foreach loop I'm trying to use to pull the course names out and put then in an unordered list.

<ul>
  <?php for( $i = 0; $i < count($JSON_array->courses); $i++ ): ?>
    echo '<li>';
    echo $JSON_array->{'courses'}[$i]->{'name'};
    echo '</li>';  
  <?php endfor; ?>
</ul>

Tis not doing anything... My source code shows empty list items

2
  • 1
    var_dump($JSON_array) Commented Nov 27, 2013 at 6:38
  • you are using for loop. use foreach will work Commented Nov 27, 2013 at 6:42

3 Answers 3

1

Try this one:

$json = '{"name": "Username","profile_name": "profile_username","profile_url": "http://myapi.net/profile_username",
"courses": [
    { "name": "English 340" },
    { "name": "History 202" },
    { "name": "Underwater Basket Weaving" }
  ]
}';//comma was missing after profile_url

$arr = json_decode($json,true);//encode as an associative array

<ul>
 <?php
  foreach($arr['courses'] as $course){
    echo '<li>';
    echo $course['name'];
    echo '</li>';  
  }
 ?>
</ul>
Sign up to request clarification or add additional context in comments.

Comments

0

you are missing , after profile_url

$json = '{
  "name": "Username",
  "profile_name": "profile_username",
  "profile_url": "http://myapi.net/profile_username",
  "courses": [
    { "name": "English 340" },
    { "name": "History 202" },
    { "name": "Underwater Basket Weaving" }
  ]
}';



$arr = json_decode($json);
?>

<ul>
  <?php for( $i = 0; $i < count($arr->courses); $i++ ): 
    echo '<li>';
    echo $arr->{'courses'}[$i]->{'name'};
    echo '</li>';  
  endfor; ?>
</ul>

2 Comments

ERMAGHERD!!! I was about to rip my shorthairs out! I rewrote that echo line about a billion times! It was the stupid JSON I was using for this exercise that was breaking the function!
yes it happens some times! If you got me right you can accept the answer.
0

Try this

<ul>
    <?php foreach($JSON_array->courses as $course): ?>
        echo '<li>';
        echo $course->name;
        echo '</li>';  
    <?php endforeach; ?>
</ul>

Updated: Moreover, your JSON is invalid!! "profile_url": "http://myapi.net/profile_username" you missing comma at the end of this line

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.