Home > Software engineering >  JSON Decode While/Foreach
JSON Decode While/Foreach

Time:02-19

I have a JSON data saved in the database. I want to put this data in a while loop and get everything in the line, but I can't. How can I do it?

[{"count":33226,"info":"","name":"cash","slot":1,"type":"item"},{"count":1,"info":{"telno":"0662052408","isim":"Bob Brc","aitlik":"steam:1100001179c1b7d","durum":"kilitli"},"name":"phone","slot":2,"type":"item"},{"count":1,"info":{"uniqueId":"3_1","keyData":"z6VAhfL3ppApIXR"},"name":"motel_key","slot":3,"type":"item"},{"count":1,"info":[],"name":"ballasbandana","slot":10,"type":"item"}]
$inventory = $karakter['inventory'];
$inventoryjson = json_decode($inventory, true); 
$items = $inventoryjson['name'];

The way it is in my database above, there are more than one item here, but I could not separate them and put them in a loop. The code field at the bottom is also the PHP field.

CodePudding user response:

What you get from this json is a multidimensional array, which means the $items = $inventoryjson['name']; will produce an error.

You could use a foreach loop to get the correct info, like so:

$inventory = $karakter['inventory'];
$items = json_decode($inventory, true);

foreach ( $items as $item ) {
    $name = $item['name'];
}
  • Related