Reputation: 1244
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
Upvotes: 1
Views: 242
Reputation: 3329
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>
Upvotes: 0
Reputation: 3170
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>
Upvotes: 1
Reputation: 1950
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
Upvotes: 0