We are have json:
{ "list":
[
{"id":"4045","value":"Xin Kai"},
{"id":"4141","value":"YZK"},
{"id":"4099","value":"ZX"}
]
}
For get value we use next code:
$json = json_decode($result, true);
foreach($json['list'] as $item) {
print $item['value'].'<br />';
}
But now we get error: Warning: Invalid argument supplied for foreach()...
Tell me please where error in code and how will be right?
asked Oct 21, 2014 at 23:21
user2881809
2 Answers 2
Your issue is that you're doing this in your code:
foreach($json->list as $item) {
When you should be doing this:
foreach($json['list'] as $item) {
As you decoded it as an array and not as an object.
Read More: json_decode()
Also, as zerkms said,
answered Oct 21, 2014 at 23:48
Darren
13.1k4 gold badges44 silver badges81 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Before json_decode you need get json in utf-8, in you exmple(if you get json in windows-1251) you need use next code:
EXAMPLE FIRST - if you want get array
//if you want get array
$json_obj = json_decode(iconv("windows-1251","utf-8",$result), true);
foreach($json_obj['list'] as $item) {
print $item['value'].'<br />';
}
EXAMPLE SECOND - if you wnt get object
//if you wnt get object
$json_obj = json_decode(iconv("windows-1251","utf-8",$result));
foreach($json_obj->list as $item) {
print $item->value.'<br />';
}
Enjoy!
answered Oct 22, 2014 at 8:33
Leo Loki
2,5956 gold badges26 silver badges31 bronze badges
Comments
lang-php
var_dump($result)? The full string. because as your example sits, it works: eval.in/208543{ "list":[{{instead of{ "list":[{