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

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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++)

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.