PHP foreach to iterate json data

37,373

Solution 1

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>

Solution 2

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'];
}

Solution 3

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

foreach($links['data'] as $item) {
    echo $item['linkUrl'];
}
Share:
37,373
nate63
Author by

nate63

Graphic designer and web developer. working with a large media entity. Well versed in multiple CMS platforms, including custom builds. I have a strong design and UI skill-set and am working on becoming a better programmer.

Updated on June 29, 2020

Comments

  • nate63
    nate63 almost 4 years

    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