Jump to content

Count items in a json string


craigward

Recommended Posts

Hi,

 

I am fairly new to PHP and have been messing around trying different things out.

 

One thing I am stuck with is being able to count the elements of a json string so I can create a loop. I can't find anything on the official PHP site and have been looking on Google for ages.

 

Would love it if someone could help me out.

 

Cheers

 

Craig

you'll have to decode it.

If you have php 5.1 ( I think it might be 5.2 ) you can use the built in function

 

 
$array=json_decode($arraywithyourjsonconents); 
foreach($array as $k=>$v)
{

}
//or 
for($a=0;$a<count($array);$a++)
{

}

if it's before that version of php then you'll have to find a php class.  I'm pretty sure there's a pear class available.

 

Thanks for the replies.

 

Here is the code I am using.

 

$flickrfeed = json_decode($filecontents);

$i = 0;
$total = count($flickerfeed);

while ($i <= $total) 
{ 
$farm = $flickrfeed->photos->photo[$i]->farm;
$id = $flickrfeed->photos->photo[$i]->id;
$server = $flickrfeed->photos->photo[$i]->server;
$secret = $flickrfeed->photos->photo[$i]->secret;

echo "<img src=\"http://farm$farm.static.flickr.com/$server/$id"._."$secret.jpg\" alt=\"Flickr Image\" />";

$i++;
}

?>

 

I have tried to use the foreach loop but havent had luck yet. but I am probably doing something wrong.

I can't get the for loop to work.

$flickrfeed = json_decode($filecontents);

for($a=0;$a<count($flickrfeed);$a++)
{ 
$farm = $flickrfeed->photos->photo[$a]->farm;
$id = $flickrfeed->photos->photo[$a]->id;
$server = $flickrfeed->photos->photo[$a]->server;
$secret = $flickrfeed->photos->photo[$a]->secret;
echo "<img src=\"http://farm$farm.static.flickr.com/$server/$id"._."$secret.jpg\" alt=\"Flickr Image\" />";
}

?>

 

But it does work if I use

for($a=0;$a<10;$a++)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.