I have this javascript function which converts a javascript array into a serialized string for use in php as array.
function js_array_serialize(a) {
var a_php = "";
var total = 0;
for (var key in a) {
++ total;
a_php = a_php + "s:" +
String(key).length + ":\"" + String(key) + "\";s:" +
String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total + ":{" + a_php + "}";
return a_php;
}
The function above does the work for associative array. But I have a multi-dimensional array and something must be done in the for loop, i can think of an other nested loop.
My javascript array is of this structure:
var a = {
'index': {
'subindex1': 'default',
'subindex2': 'default'
},
'index2': {
'subindex1': 'default',
'subindex2': 'default'
}
};
Any help is appreciated. Thanks!
-
2Have you tried turning the array into JSON, that way both PHP and javascript can use it with ease.Rick Kuipers– Rick Kuipers2012年01月28日 16:03:43 +00:00Commented Jan 28, 2012 at 16:03
-
It's ok via php, I just need to do it via client side without the use of ajax or php to generate the serialized string.user558134– user5581342012年01月28日 16:10:32 +00:00Commented Jan 28, 2012 at 16:10
1 Answer 1
You seem to be reinventing the JSON wheel. How about this:
function js_array_serialize(a) {
return JSON.stringify(a);
}
The JSON.stringify function is natively built-in modern browsers. And if you want to support legacy browsers simply include the json2.js script to your page.
Never use string concatenations to build JSON. There are much more cases that you will need to handle: things like properly escaping the values. Think for example if the value contains quotes? It will break your serialization algorithm.