I need to convert an object into JSON using a php script.
I wrote this code in a loop cycle:
$zaino->rows[$num_oggetti]->item = $oggetto;
$zaino->rows[$num_oggetti]->amount = $num;
After the loop cycle I convert the object into json: json_encode($zaino);
This is what I get:
{"rows":{"1":{"item":"Soffio di Morte","amount":"1"},"2":{"item":"Pietra Anima di Ferro","amount":"11"},"3":{"item":"Pietra Anima di Legno","amount":"12"}}
But I need something like:
{"rows":[{"item":"Soffio di Morte","amount":"1"},{"item":"Pietra Anima di Ferro","amount":"11"},{"item":"Pietra Anima di Legno","amount":"12"}]}
without numbers between ""
, so that I can easily get the values using for example $zaino->rows[1]->item
after calling a json_decode
. How can I do it?
The problem is that $num_oggetti
is a string value, not a number (yes, numeric, but not a number). This tells PHP that you are setting a key instead of an index.
If you do not need the actual index you could do something like:
$zaino->rows[] = [
'item' => $oggetto,
'amount' => $num
];
This way you leave the index generation entirely up to PHP and you'll get the json output you want.