0

I have json like below, how can i loop each id

{
    "id1": {
        "AreaN": "\u30ef\u30fc\u30eb\u30c9\u30d0\u30b6\u30fc\u30eb",
        "AreaM": "\uff9c\uff70\uff99\uff84\uff9e\uff8a\uff9e\uff7b\uff9e\uff70\uff99"
    },
    "id2": {
        "AreaN": "\u30ef\u30fc\u30eb\u30c9\u30d0\u30b6\u30fc\u30eb",
        "AreaM": "\uff9c\uff70\uff99\uff84\uff9e\uff8a\uff9e\uff7b\uff9e\uff70\uff99"
    }
}

I tried but it does not get all the ids, i cant change the json.

$json = json_decode($doc);
if( count($json) > 0 )
{
    foreach($json as $area)
    {

    }
}

In my case the ids i want to get are not inside an array. Is it possible to loop the ids and keep them as objects, i prefer object access than using square brackets.

7
  • Working stackoverflow.com/questions/49483929/… Commented Mar 26, 2018 at 4:24
  • Your code looks correct. What is it that you are trying to achieve in your foreach? Commented Mar 26, 2018 at 4:25
  • @Avi_B im trying to get each id object in a loop Commented Mar 26, 2018 at 5:23
  • it seems my code was correct there was an error somewhere else should i delete this question? Commented Mar 26, 2018 at 6:12
  • @tsukimi I think probably you're using PHP7.2 and above, and stdClass is not implementing Countable interface. Refer here: php.net/manual/en/… So to fix this, you just change to assoc array, i.e. json_decode($doc, 1) Commented Mar 26, 2018 at 6:26

1 Answer 1

2
$json = json_decode($doc, 1);
foreach ($json as $id => $area) {
    // $id is "id1", "id2"
    // $area is AreaN & AreaM
}

the 2nd param for json_decode if true will return as array, otherwise will be object

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.