简体   繁体   English

将PHP assoc数组转换为json对象

[英]Converting PHP assoc array to json object

I have an assoc array in PHP: 我在PHP中有一个assoc数组:

foreach ($result as $value) {   
    $x++;
    $data += array("nds" => array($x => $x), "eds" => array(), "an" => array($x => $this->model->getLng($value)));
}

I send this array to a JS file and it prints like below: 我将此数组发送到JS文件,其打印如下:

{"nds":{"1":1},"eds":[],"an":{"1":[45.4423073,-75.7979993]}}

However, I cannot reach nds because this returns undefined: 但是,我无法到达nds因为这返回的是undefined:

console.log(data.nds);

PHP is just sending a string to the JS file. PHP只是将字符串发送到JS文件。 You would first need to set a variable equal to that string: 您首先需要设置一个等于该字符串的变量:

<script>
  var json = '<?= $data; ?>';
</script>

Now we have a JS variable json , but it needs to be converted to an object to reference the nds property. 现在我们有了一个JS变量json ,但是需要将其转换为一个对象以引用nds属性。 We can do that with JSON.parse() : 我们可以使用JSON.parse()做到这一点:

<script>
  var json = '<?= $data; ?>';
  var data = JSON.parse(json);

  console.log(data.nds); // Object {1: 1}
</script>

@RobM made a good point that we don't even need to parse this as a string and can just set the variable as the JSON dump: @RobM提出了一个很好的观点,我们甚至不需要将其解析为字符串,而只需将变量设置为JSON转储即可:

<script>
  var data = <?= $data; ?>;
  console.log(data.nds); // Object {1: 1}
</script>

This still requires you to pass the JSON data ( { "nds": { "1": 1 }, "eds": [], "an": { "1": [ 45.4423073, -75.7979993 ] } } ) from your PHP script into a JS variable. 这仍然需要您传递JSON数据( { "nds": { "1": 1 }, "eds": [], "an": { "1": [ 45.4423073, -75.7979993 ] } } )将PHP脚本转换为JS变量。

You can use the jQuery JSON parser or the standard Javascript JSON parser: 您可以使用jQuery JSON解析器或标准Javascript JSON解析器:

var data = '{"nds":{"1":1},"eds":[],"an":{"1":[45.4423073,-75.7979993]}}';

var d = $.parseJSON(data);  // jQuery
console.log(d['nds']);

var j = JSON.parse(data);   // Javascript
console.log(j['nds']);

example: http://jsfiddle.net/bb7ak6L5/ 例如: http//jsfiddle.net/bb7ak6L5/

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

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