Rabu, 04 September 2019

2 Dimensional Array to JSON data in Javascript

Quick posting on how to convert 2 dimensional javascript array to JSON data. Source!
  
var questions = [];
 
 for(i=0;i<3;i++) {
    questions[i] = {};
    questions[i]["question"] = "hey";
    questions[i]["rating"] = "123";
 });


var encoded = JSON.stringify(questions);
console.log(encoded);

Take a look at the third code line! With this way, you send the second array dimension as array object. If you send this data with AJAX to a PHP code, you should put 'true' as the second argument on json_decode php function. It will convert the JSON data into a php array.
  
<?php

$myarray = json_decode(encoded, true);

?>

1 komentar: