0

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?

1
  • try something like this <?php echo "var damages = ".json_encode($damage_array); ?>; Commented Dec 17, 2015 at 20:17

2 Answers 2

4

try this:

var damagesAsString = '<?php echo json_encode($damage_array); ?>'; // json string
var damages = JSON.parse(damagesAsString); // json object
Sign up to request clarification or add additional context in comments.

2 Comments

The one you posted before this one worked better, it returns {"lf":4,"rf":9,"lrfo":22,"rrfo":19,"lrfi":22,"rrfi":19,"lrro":15,"rrro":10,"lrri":15,"rrri":10}, why did you change?
JSON.parse() parses string to json object. Do you want string or object as result?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.