简体   繁体   中英

Converting PHP assoc array to json object

I have an assoc array in PHP:

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:

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

However, I cannot reach nds because this returns undefined:

console.log(data.nds);

PHP is just sending a string to the JS file. 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. We can do that with 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:

<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.

You can use the jQuery JSON parser or the standard Javascript JSON parser:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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