php,js创建json数据

时间:2013-03-02 10:38:32

标签: php javascript json

在php中我有类似的东西:

$i=1; 
foreach ($result as $row){
    $outp['fields'][$i]['id']=$row['id'];
    $outp['fields'][$i]['x']=$row['x'];
    $outp['fields'][$i]['y']=$row['y'];
    $outp['fields'][$i]['type']=$row['type'];
    $i++;
}
echo json_encode($outp)

在JS中:

success: function(data) {
  var map = eval('(data)');
}

这是JSON输出:

{"fields":
     {"1":{"id":9521,"x":21,"y":96,"type":2},
      "2":{"id":9522,"x":22,"y":96,"type":3},
      "3":{"id":9523,"x":23,"y":96,"type":1},
      "4":{"id":9930,"x":30,"y":100,"type":3}
     } 
}

我想为每个字段编写html代码(在这种情况下为4个字段)。 我该怎么做?这可以将var map转换为数组吗?

由于

1 个答案:

答案 0 :(得分:0)

试试这个:

for(var i=1;i<=Object.keys(map["fields"]).length;i++){
    console.log(map["fields"][i]["id"]); //id
    console.log(map["fields"][i]["x"]);  //x
    console.log(map["fields"][i]["y"]);  //y
}