Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach to iterate json data

Tags:

json

foreach

php

I've been working with json for the first time and php for the first time in a long time and I've hit a wall regarding the two.

I have created a javascript file with a json feed in it and have successfully decoded it using php and can now access the data (one item at a time) but I'm hitting a snag when trying to iterate over it and spit out list items using all of the data.

any help with this would be appreciated.

the josn looks like this:

{
    "data": [
        {
            "name": "name1",
            "alt": "name one",
            "imgUrl": "img/icons/face1.png",
            "linkUrl": "linkurl"
        },
        {
            "name": "name2",
            "alt": "name two",
            "imgUrl": "img/icons/face2.png",
            "linkUrl": "linkurl"
        }
    ]
}

and the php:

<?php
$json_url = "js/tiles/jsonfeed.js";
$json = file_get_contents($json_url);
$links = json_decode($json, TRUE);
?>
<ul>
    <li>
    <a href="<?php echo $links['data'][1]['linkUrl'] ?>"><img scr="<?php echo $links['data'][1]['imgUrl']; ?>" alt="<?php echo $links['data'][1]['alt']; ?>" class="share-icon" /></a>
    </li>
</ul>

Now obviously this will only grab the information in the second array slot and I'm aware that there is a more efficient way to write the list items, without jumping in and out of php, and that will be cleaned up shortly.

The issue I'm having is trying to wrap this in a foreach loop to spit out a list item for each item in the json feed. Being new to json, and having not touched php in some time I'm having a hard time formatting the loop properly and grabbing the appropriate data.

Could someone please help me get this working properly?

Thanks

like image 295
nate63 Avatar asked Jun 28 '12 15:06

nate63


3 Answers

You would simply need to foreach the data and then work with each of the children in turn:

foreach ($links['data'] AS $d){
    echo $d['linkUrl'];
}
like image 80
ashryalls Avatar answered Nov 19 '22 18:11

ashryalls


This should do the job:

<?php
$json_url = "js/tiles/jsonfeed.js";
$json = file_get_contents($json_url);
$links = json_decode($json, TRUE);
?>
<ul>
<?php
    foreach($links['data'] as $key=>$val){ 
?>
    <li>
    <a href="<?php echo $val['linkUrl'] ?>">
        <img scr="<?php echo $val['imgUrl']; ?>" alt="<?php echo $val['alt']; ?>" class="share-icon" />
    </a>
    </li>
<?php
    }
?>
</ul>
like image 45
Havelock Avatar answered Nov 19 '22 19:11

Havelock


Your foreach loop should iterate over $links['data'] like this for example:

foreach($links['data'] as $item) {
    echo $item['linkUrl'];
}
like image 1
Brian Glaz Avatar answered Nov 19 '22 19:11

Brian Glaz