简体   繁体   English

带有JavaScript对象的PHP数组到JavaScript

[英]PHP array with JavaScript objects to JavaScript

If I have an array in JS like this: 如果我在JS中有这样的数组:

{
 "car": "BMW",
 "count": 7 
}

I can generate it from PHP quite easy using this array: 我可以使用此数组从PHP轻松生成它:

array(
       'car' => 'BMW',
       'count' => 7,
)

and json_encode. 和json_encode。 This is not a problem. 这不是问题。

But what if I have an array in JS like this: 但是如果我在JS中有这样的数组怎么办:

{
   "center": new google.maps.LatLng(-34.397, 150.644),
   "zoom": 8
}

is there also some nice way how to produce it from PHP? 还有一些不错的方法如何从PHP生成它吗?

The method above fails because JSON put quotes around "new google.maps.LatLng(-34.397, 150.644)". 上面的方法失败了,因为JSON在“ new google.maps.LatLng(-34.397,150.644)”周围加上了引号。

JSON doesn't support custom types. JSON不支持自定义类型。 It's just meant for passing data and to be available to any consumer, whereas google.maps.LatLng() isn't really " data ." 它只是用于传递数据并可供任何消费者使用,而google.maps.LatLng()并不是真正的“ 数据”

So, you'll have to accomplish this in 2 steps: 因此,您必须分两步完成此操作:

  1. You can include the values needed in another PHP array for the JSON: 您可以在另一个PHP array中包含JSON所需的值:

     array( 'center' => array( 'lat' => -34.397, 'lng' => 150.644 ), 'zoom' => 8 ) 
     { "center": { "lat": -34.397, "lng": 150.644 }, "zoom": 8 } 
  2. Then, once parsed to a JavaScript Object , say data : 然后,一旦解析为JavaScript Object ,则说出data

     data.center = new google.maps.LatLng(data.center.lat, data.center.lng); 

    And, if there are numerous examples of such objects in the data, you can specify a reviver function to try to recognize them and create the instances: 并且,如果数据中存在大量此类对象的示例,则可以指定reviver function以尝试识别它们并创建实例:

     // parse, creating `google.maps.LatLng` from any { lat: ..., lng: ..., ... } var data = JSON.parse(jsonString, function (key, value) { if (typeof value === 'object' && value.lat && value.lng) { return new google.maps.LatLng(value.at, value.lng); } else { return value; } }); 

    Example: http://jsfiddle.net/XXbUU/ 示例: http//jsfiddle.net/XXbUU/


Side note: JSON and JavaScript make a stronger distinction between " array " types than PHP does. 旁注:与PHP相比,JSON和JavaScript在“ 数组 ”类型之间有更强的区分。

  • " Associative " array s in PHP become Object s in JSON and JavaScript. PHP中的“ 关联array在JSON和JavaScript中成为Object
  • " Non-associative " array s in PHP become Array s in JSON and JavaScript. PHP中的“ 非关联array变成JSON和JavaScript中的Array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM