PHP foreach to iterate json data

I am working with json for the first time and php for the first time in a long time, and I hit the wall for two.

I created a javascript file with the json channel in it and successfully decoded it with php and now I can access the data (one element at a time), but I click on it when I try to iterate through it and spit using all the data.

Any help with this would be appreciated.

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 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 it’s obvious that this will only capture information in the second slot of the array, and I know that there is a more efficient way to write list items, without jumping and exiting php, and this will be cleared soon.

The problem I am facing is that she is trying to wrap this in a foreach loop to spill out a list item for each item in the json feed. Being new to json and not touching php for some time, it is not easy for me to format the loop correctly and capture the relevant data.

Can someone help me make this work correctly?

thanks

+4
source share
3 answers

This should complete the task:

 <?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> 
+3
source

You just need to look at the data, and then work with each of the descendants:

 foreach ($links['data'] AS $d){ echo $d['linkUrl']; } 
+6
source

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

 foreach($links['data'] as $item) { echo $item['linkUrl']; } 
0
source

All Articles