duanliao6789 2016-11-20 18:02
浏览 52
已采纳

将php数组格式化为格式良好的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:

Javascript

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>
 </select>

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?

  • 写回答

1条回答 默认 最新

  • doutou7549 2016-11-20 18:16
    关注

    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]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题