Symfony 4 – PHP convert multidimensional array to javascript

Symfony 4 – PHP convert multidimensional array to javascript

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 !

Source: Symfony Questions

Leave a Reply

Your email address will not be published. Required fields are marked *