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.

tsukimi
  • 1,605
  • 2
  • 21
  • 36
  • Working https://stackoverflow.com/questions/49483929/loop-json-with-no-array-php – B. Desai Mar 26 '18 at 04:24
  • Your code looks correct. What is it that you are trying to achieve in your foreach? – Avi_B Mar 26 '18 at 04:25
  • @Avi_B im trying to get each id object in a loop – tsukimi Mar 26 '18 at 05:23
  • it seems my code was correct there was an error somewhere else should i delete this question? – tsukimi Mar 26 '18 at 06:12
  • @tsukimi I think probably you're using PHP7.2 and above, and stdClass is not implementing Countable interface. Refer here: http://php.net/manual/en/migration72.incompatible.php#migration72.incompatible.warn-on-non-countable-types So to fix this, you just change to assoc array, i.e. `json_decode($doc, 1)` – Js Lim Mar 26 '18 at 06:26
  • @JsLim no its actually working as is with no changes, so really this question and answers have no worth so should delete this question – tsukimi Mar 26 '18 at 06:45
  • well seems like i cant delete so ill just accept answer! – tsukimi Mar 26 '18 at 07:41

1 Answers1

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

Js Lim
  • 3,625
  • 6
  • 42
  • 80