Welcome Guest, Not a member yet? Register   Sign In
Help with Looping through an object
#3

Hi,

Your json format is incorrect. json keys should be in double quotes.

It should look like this:

Code:
{
"products": [
   {
       "id": "D-MFIN-2-150MB",
       "pur_currency": "NN",
       "topup_amount": 200,
       "price": 200,
       "data_amount": "150"
   },
   {
       "id": "D-MFIN-2-1",
       "pur_currency": "NN",
       "topup_amount": 1000,
       "price": 1000,
       "data_amount": "1000"
   }
]
}

Decode as normal
Code:
$list = json_decode($json);

Your for loop would then iterate like this:

Code:
for ($i=0; $i < count($list->products); $i++) {
echo "Item no. {$i} is {$list->products[$i]->id} <br>";
}

or, as jreklund points out, foreach is the best way to iterate:

Code:
foreach ($list->products as $key => $row) {
echo "Item no. {$key} is {$row->id} <br>";
}
Reply


Messages In This Thread
Help with Looping through an object - by enelson - 11-10-2018, 11:17 AM
RE: Help with Looping through an object - by paulkd - 11-11-2018, 12:52 AM



Theme © iAndrew 2016 - Forum software by © MyBB