Help with Looping through an object |
Hi all,
i have a JSON that looks similar to one shown below: Code: products: [ I want to loop through it and display in a select tag. I've failed to do that so far. To test I converted the JSON to PHP objects using $list = json_decode), then: PHP Code: for ($i=0; $i < count($list); $i++) { Code: A PHP Error was encountered PHP Code: for ($i=0; $i < count($list); $i++) { Code: An uncaught Exception was encountered PHP Code: for ($i=0; $i < count($list); $i++) { My question, how can I get id, pur_currency, etc... from the $list variable. Your answer is appreciated.
It should be used like this as your JSON are stored as objects inside an array.
{$list[$i]->id} $list = array with multiple arrays. $list[$i] = returns an object. $list[$i]->id = returns the ID inside that object. Personally I would just use a foreach loop instead. PHP Code: foreach($list as $row) { In case you don't need the position in that array.
Hi,
Your json format is incorrect. json keys should be in double quotes. It should look like this: Code: { 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++) { or, as jreklund points out, foreach is the best way to iterate: Code: foreach ($list->products as $key => $row) {
It is faster to get the count first before running a for loop.
Otherwise you are calling the count method on each loop irritation. PHP Code: $count = count($list->products); What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
Another issue I have is that I want to sort $list in ascending order by "data_amount".
asort(), ksort() etc are returning bool(true) instead of the $list objects - and they should be. Any ideas as to how I can sort the $object?
Do you have control of what is producing the json?
If so, maybe you can use that process to sort (e.g. SQL query)
You could decode the json into an associated array sort it and then encode it back to json
and then create your list. What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
Hi,
I got this answer from https://stackoverflow.com/questions/4282...ect-fields Code: $list = json_decode($json); |
Welcome Guest, Not a member yet? Register Sign In |