How to serialize an array in JQuery with the same PHP schema?

1

way to serialize an array in PHP

$value = array(array('Nombre','Adam'),array('Nombre','Exael'));
echo serialize($value);
/*a:2:{i:0;a:2:{i:0;s:6:"Nombre";i:1;s:4:"Adam";}i:1;a:2:{i:0;s:6:"Nombre";i:1;s:5:"Exael";}} */

Now I need to serialize the same but in Jquery

var values = [['Nombre','Adam'],['Nombre','Exael']];
?
    
asked by Ing. Marquez Adam 24.10.2016 в 20:22
source

1 answer

2

You can make a custom function in javascript that serializes the array in the same way that serilaize does and can be deserialized with unserilize , but does not make much sense because both Javascript and php share an API that serves to exchange structured data (Arrays, Objects or a combination of these) called JSON.

JSON is the acronym for Javascript Object Notation and is currently the most widely used technique for data transfer on all platforms, including Javascript, PHP, Java, C #, Ptyhon, etc. because it's simple, it has a relatively low overhead (compared to XML or HTML for example) and all platforms support it.

So, in Javascript you serialize with, JSON.stringify() :

var estructura = [["a","b"],{ "c": "d"}];

console.log(
  JSON.stringify(estructura)
)

You deserialize with JSON.parse() .

var json = '[["a","b"],{ "c": "d"}]';

console.log(
  JSON.parse(json)
)

So far so good, the results are almost identical, but this happens because JSON is native to javascript.

In PHP you have the functions, json_decode to deserialize and json_encode to serialize.

$value = json_decode('[["Nombre","Adam"],["Nombre","Exael"]]');
echo serialize($value);
/*a:2:{i:0;a:2:{i:0;s:6:"Nombre";i:1;s:4:"Adam";}i:1;a:2:{i:0;s:6:"Nombre";i:1;s:5:"Exael";}} */


$value2 = array(array('Nombre','Adam'),array('Nombre','Exael'));
var $json = json_encode($value2);
/*[["Nombre","Adam"],["Nombre","Exael"]]*/

Basically, these methods allow you to exchange complex data structures between javascript, php and many other technologies.

Finally, if you are aware that it is a REST API or a REST Full API, these APIs are based in the vast majority of cases in the JSON format, for the reasons explained above.

Do not worry about not mentioning JQuery, it is based on javascript and is compatible and in fact uses the JSON API of the browser.

Salu2

    
answered by 25.10.2016 / 02:36
source