0

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
15
  • 1
    @learner what do you get in that var_dump($result)? The full string. because as your example sits, it works: eval.in/208543 Commented Oct 21, 2014 at 23:32
  • 1
    ideone.com/zzoQHd - it works Commented Oct 21, 2014 at 23:34
  • 1
    @zerkms in your code { "list":[{{ instead of { "list":[{ Commented Oct 21, 2014 at 23:37
  • 1
    That string has broken UTF characters. JSON string must be a valid UTF string. But even that string does work fine (on php 5.3) Commented Oct 21, 2014 at 23:40
  • 1
    @zerkms i see it, me need delete this or other action? Commented Oct 21, 2014 at 23:47

2 Answers 2

1

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,

>>> windows-1251 <<< JSON document must be in UTF-8

answered Oct 21, 2014 at 23:48
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.