0

I am working on a Symfony project and need to loop through data to populate saved fields in a form (specifically the number of bed types in a property). I save the data in the database table as a json string, as follows:

{"2":"5","3":"0","4":"0","5":"0","6":"0","7":"0"}

This JSON follows the structure "BEDID": NUMBER OF BEDS. I implemented the solution regarding decoding json in twig as stated here https://stackoverflow.com/a/14504988/5194337 but I am having trouble actually being able to access each specific value in the decoded json. I use this in the twig template to decode the json (based on the fact my data is stored in a variable called specifics and website.id references one of multiple websites owned by the user:

{% set beds = specifics[website.id].0.standardBedTypes|json_decode  %}

So, once I do this, I try and access the value of each number of beds as follows:

{{ beds[standard_bed.id] }}

standard_bed being the value in the for loop. But, when I load the page I get the following error:

Impossible to access a key "2" on an object of class "stdClass" that does not implement ArrayAccess interface.

I guess this means that the decoded value of the json is technically not an array, but I cannot think of any other method of referencing each value, so help with this is appreciated.

Michael Emerson
  • 1,774
  • 4
  • 31
  • 71
  • Please add some code... It's hard to follow what is what, even more so to create a local test for your description. That said, is it really a good idea to decode the string in the template? Why not have the model class do it? This way you don't repeat the same code in multiple places. – Yoshi Jan 24 '18 at 11:00

1 Answers1

2

From the documentation here, you can pass it as an option. See the options here.

You want to pass JSON_OBJECT_AS_ARRAY

Decodes JSON objects as PHP array.

So basically you want to do:

{% set beds = specifics[website.id].0.standardBedTypes|json_decode(constant('JSON_OBJECT_AS_ARRAY'))  %}

If you want to access to objects properties, you can do it using the attribute function.

Strnm
  • 1,006
  • 2
  • 9
  • 21