1

Hello I've this array in Symfony on my controller:

    $array = [
        "label" => [
            "january",
            "february"
        ],
        "data" => [
            0,
            1
        ]
    ];

I wish I could convert it for use in Javascript.

The goal is that I can get in JS:

["january", "february"] and [0,1]

to use them as array variables

I tried json_encode($array), it works but I can't access to my array using {{array["label"}} in Twig in the Javascript block

Can someone help me please ?

EDIT : Okay guys, it works now, I did this :

Controller :

    return $this->render('products/index.html.twig', [
        "report" => json_encode($report),
    ]);

index.html.twig (javascript bloc)

const data = {{report | raw}};

Thanks all !

1
  • Please, add to your question the part of your controller that return the response and your twig, where you try to read your data. Commented Feb 6, 2020 at 15:55

3 Answers 3

1

You do not have to call JSON.parse since the output of json_decode is a javascript literal. Just assign it to a variable.

var yourArray = <?php echo json_encode($array); ?>;

You can access property like this

alert(yourArray[0].Key);
Sign up to request clarification or add additional context in comments.

2 Comments

No it doesn't work, I've this error : Impossible to access a key ("0") on a string variable ("{"label":["January","February"],"data":["0","1"]}").
Try like this yourArray[0][1] or Try like this alert(yourArray[0].1); See here how to access data in array jsfiddle.net/9f5zn2s6
0

You can try use:

PHP:

$array = [
    "label" => [
        "january",
        "february"
    ],
    "data" => [
        0,
        1
    ]
];
$response = new Response(json_encode($array));
$response->headers->set('Content-Type', 'application/json');
return $response;

JavaScript:

var data = JSON.parse(response);
console.log(data.label)

Hope help you.

2 Comments

Argh, no it doesn't work. I'm using Symfony, so I've to access my variable using var data = JSON.parse({{response}}) But it doesn't work
@eronn could you please provide here dd(data)?
0

What you get is a Json string, not an object, you first have to parse it in Javascript.

const data=JSON.parse(array);

4 Comments

Incorrect, if this was being pulled into a JS string then yeah that would be the case, but since we are using PHP we can literally just assign the json_encode result by echoing it into the script like: let arr = <?=json_encode($array); ?>;
No it doesn't work, I've this error in the console :``` Uncaught SyntaxError: Unexpected token '&' ```
@JoshWood he's in his twig view, not in a simple HTML/PHP model. What you're suggesting isn't going to works
@Preciel My apologies then

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.