JordanBarber
JordanBarber

Reputation: 2101

Converting PHP array into JS variable

I need to convert my php array into a javascript variable. I am using json_encode to do this but it is returning with some errors. I have a php variable:

<?php $damage_array = $listing->tire_detail->damage_details; ?>

which prints out to be

Array ( [lf] => 4 [rf] => 9 [lrfo] => 22 [rrfo] => 19 [lrfi] => 22 [rrfi] => 19 [lrro] => 15 [rrro] => 10 [lrri] => 15 [rrri] => 10 )

Then in my javascript I have:

var damages = "<?php echo json_encode($damage_array); ?>";

which prints out to:

var damages = "{"lf":4,"rf":9,"lrfo":22,"rrfo":19,"lrfi":22,"rrfi":19,"lrro":15,"rrro":10,"lrri":15,"rrri":10}";

Can someone please help me clean this out so that my js variable is an actual array?

Upvotes: 0

Views: 40

Answers (2)

geggleto
geggleto

Reputation: 2625

I think you can just do this... var damages = <?php echo json_encode($damage_array); ?>;

Upvotes: 1

madox2
madox2

Reputation: 51841

try this:

var damagesAsString = '<?php echo json_encode($damage_array); ?>'; // json string
var damages = JSON.parse(damagesAsString); // json object

Upvotes: 4

Related Questions