luca.p.alexandru
luca.p.alexandru

Reputation: 1750

PHP generate javascript objects with multiple properties

I did a function that generates from a php array a javascript object, for instance

$this->routes = array(
        'Module' => array(
            'Route1' => $renderer->url('route1', array('lang' => $lang_short)),
            'Route2' => $renderer->url('route1', array('lang' => $lang_short)),
        )
    );

My function will generate a javascript object like

{Static: {Module: {Route1: 'route1', Route2: 'route2'}}}

So I can access this in js like

Static.Module.Route1

The "problem" is the method I made handles arrays just with 2 nested arrays, not more. What would be a nice and easy way to achieve this?

Upvotes: 0

Views: 35

Answers (1)

Steven Mercatante
Steven Mercatante

Reputation: 25315

Use the native json_encode function, instead of your custom function.

Upvotes: 4

Related Questions