Swolschblauw Swolschblauw - 1 year ago 84
Javascript Question

Format php array to well formatted array/object for javascript

In PHP I've the following array:

$variation = [
attribute_label => "Choose your Color",
attribute_name => "pa_choose-your-color",
variations => [
"819" => "Red",
"820" => "Blue",
"821" => "Green"

I'm sending this array json encoded back to my Ajax call.

After the json_encode the array looks like this:


This kind of array is not very handy for looping in Javascript.

In the loop I'm appending the attribute_label to the label before the select box and the attribute_name to a data-id attribute for the select box, the variations are the options in the select box. The keys of the variations are not optional they are the ids of the variations and used to append to the data-id of an option in the select box.
I've did it before with an easier formatted array but because a product can have multiple variations I had to change the format of the array.

Example of HTML

<label>Choose your Color</label>
<select data-id="pa_choose-your-color">
<option data-id="818">Red</option>
<option data-id="819">Blue</option>

Do I have to change the format of the PHP array or is there a way to loop trough this kind of objects in javascript?

Answer Source

Try this for the loop constructing your options:

var obj = {"attribute_label":"Choose your Color","attribute_name":"pa_choose-your-color","variations":{"819":"Red","820":"Blue","821":"Green"}};

for (variation in obj.variations) {
  console.log("Data ID: " + variation);
  console.log("Color: " + obj.variations[variation]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download