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

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示