I'm trying to convert a PHP multidimensional array to a javascript array WITHOUT using json encoder because of the version of the server.
Exemple of a multidimensional Array :
Array (
[0] => Array (
[0] => 18
[1] => Région Grand EST
[2] => GE )
[1] => Array (
[0] => 17
[1] => Région Grand OUEST / NORD
[2] => GO N )
[2] => Array (
[0] => 25
[1] => Région Grand OUEST / SUD
[2] => GO S )
)
Currently for no multidimensional array i'm using this function :
function js_str($s) {
return '"' . addcslashes($s, "0円..37円\"\\") . '"';
}
function js_array($array) {
if (is_array($array)) {
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
return '[-1]';
}
But i can't use it for multidimensional, i'm trying to do somthing similar recursively to do it with any size of array.
To get a result like :
myArray = [[18, 'Région Grand EST', 'GE'],[17, 'Grand OUEST / NORD', 'GO N'], [25, 'Région Grand OUEST / SUD', 'GO S']];
It's really hard to find an answer without json_encode, thanks for your help. (Yes i'm developping on a prehistoric server)
-
2Why not am external library that creates a JSON? packagist.org/search/?q=JSONDamien Pirsy– Damien Pirsy2016年01月27日 16:27:14 +00:00Commented Jan 27, 2016 at 16:27
-
"Because of server version" is a pretty weak reason against using JSON. There's gotta be external libraries for virtually any PHP version that provide a JSON encoder. You're basically in the process of poorly reinventing one yourself.deceze– deceze ♦2016年01月28日 13:33:22 +00:00Commented Jan 28, 2016 at 13:33
2 Answers 2
I would approach this problem with a recursive function like this:
function js_array($array) {
if (is_array($array)) {
$temp = array();
$output = '[';
foreach ($array AS $key=>$value) {
$temp[] .= "'$key':" . js_array($value);
}
$output .= implode(',', $temp);
$output .= "]";
} else {
$output .= "'$array'";
}
return $output;
}
What we're doing here is evaluating each element of the array to see if it is also an array. Each level drills down into itself until we are left with simple key:value pairs.
You can edit for special characters or to drop the array keys if you want.
1 Comment
Thx to Danielml01 for his help. Here the solution used :
function js_array($array) {
if (is_array($array)) {
$temp = array();
$isObject = false;
foreach ($array AS $key=>$value) {
if (is_numeric($key))
$temp[] .= js_array($value);
else {
$isObject = true;
$temp[] .= "'$key':" . js_array($value)."";
}
}
if ($isObject)
$output = "{".implode(',', $temp)."}";
else
$output = "[".implode(',', $temp)."]";
}
else
$output = "'".$array."'";
return $output;
}
Comments
Explore related questions
See similar questions with these tags.