Majid Sajadi Majid Sajadi - 2 months ago 10
JSON Question

Access values in nested foreach PHP

I have a JSON file. (Steam API). I want to display player inventory in my website. I use this url: https://steamcommunity.com/id/majidsajadi/inventory/json/730/2

Then I decode it with

json_decode
function.

Now there are two arrays: rgInventory and rgDescription. I need to check if class id in rgInventory and classid in rgDescription match I use some of values in igDescription.

So I think I should use 2 foreach loop and a if condition to check if class id match. then I echo out the information I need.

The question is how should I use nested foreach?

Answer

You can use two nested foreach loops like this:

Assuming that $decoded_data is your decoded data after applying json_decode() function on the end result, like this: $decoded_data = json_decode($your_json_data, true);

foreach($decoded_data['rgInventory'] as $arr1){
    foreach($decoded_data['rgDescriptions'] as $arr2){
        if($arr1['classid'] == $arr2['classid']){

            // both the classid matches
            // your code

        }
    }
}
Comments