Page 1 of 1

Need Help Printing an Array

Posted: Tue Oct 20, 2009 9:51 am
by ulyssesr
Hello. I'm new to this forum. I thought I give this forum a try. I've been fighting with printing an array for a couple of hours now. I need to be able to display it on the screen, but I can't seem to figure it out. The value of the $json array is:

[{"position":null,"name":"#jobs","query":"#jobs","id":1431729,"created_at":"Thu Aug 27 19:30:55 +0000 2009"},{"position":null,"name":"ubuntu","query":"ubuntu","id":1449458,"created_at":"Fri Aug 28 21:50:21 +0000 2009"},{"position":null,"name":"linux","query":"linux","id":1650471,"created_at":"Sat Sep 12 00:20:18 +0000 2009"},{"position":null,"name":"#wordpress","query":"#wordpress","id":1912615,"created_at":"Tue Sep 29 11:18:41 +0000 2009"}]

This is my code: (I've updated the code. It's an API call to Twitter)

Code: Select all

 
$contents = @file_get_contents("http://twitter.com/saved_searches.json"); 
$json = json_decode($contents);
foreach ($json as $saved_search) {
  echo $saved_search->name;
}
 
What am I doing wrong?

Re: Need Help Printing an Array

Posted: Tue Oct 20, 2009 10:01 am
by Mark Baker
Works for me.

What are you seeing when you echo $saved_search->name

Re: Need Help Printing an Array

Posted: Tue Oct 20, 2009 10:11 am
by ulyssesr
Mark Baker wrote:Works for me.

What are you seeing when you echo $saved_search->name
Actually, I'm not even getting past that point. I'm getting an foreach() error. It says:

"Invalid argument supplied for foreach()"

It's baffling. Something is wrong with the foreach argument, but I can't figure out what or why.

Re: Need Help Printing an Array

Posted: Tue Oct 20, 2009 11:49 am
by Mark Baker
What version of PHP are you running?

Re: Need Help Printing an Array

Posted: Tue Oct 20, 2009 7:35 pm
by John Cartwright
Try treating the decoded json as an associative array

Code: Select all

$json = json_decode($contents, true);
foreach ($json as $saved_search) {
  echo $saved_search['name'];
}

Re: Need Help Printing an Array

Posted: Wed Oct 21, 2009 2:30 am
by ulyssesr
Mark Baker wrote:What version of PHP are you running?
My host is Dreamhost. I believe it's running default which according to their site is: PHP 5.2.6.

Re: Need Help Printing an Array

Posted: Wed Oct 21, 2009 2:31 am
by ulyssesr
John Cartwright wrote:Try treating the decoded json as an associative array
Thanks, John. I tried the code you suggested. Still not working. I'm getting a "Invalid argument supplied for foreach()" error. I've updated my original code. It's actually an API call to Twitter. See original code above. In the meantime, I'll do some more research on associative arrays.