note 56437 deleted from function.print-r by peehaa
| From: | peehaa@php.net | Date: | Fri, 12 Jul 2013 16:23:42 +0000 |
| Subject: | note 56437 deleted from function.print-r by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195592@lists.php.net to get a copy of this message | ||
Note Submitter: jamin42b at gmail dot com
----
Here's a short function that can export php arrays to javascript arrays.
<?php
function php_to_js($array, $base) {
$js = '';
foreach ($array as $key=>$val) {
if (is_array($val)) {
$js .= php_to_js($val, $base.(is_numeric($key) ? '['.$key.']' :
"['".addslashes($key)."']"));
} else {
$js .= $base;
$js .= is_numeric($key) ? '['.$key.']' :
"['".addslashes($key)."']";
$js .= ' = ';
$js .= is_numeric($val) ? ''.$val.'' :
"'".addslashes($val)."'";
$js .= ";\n";
}
}
return $base." = new Array();\n".$js;
}
?>
Example use:
<?php
$my_array = array('gdsag' => 4, 'hello', array(5, 6));
echo '<script>'.php_to_js($my_array).'</script>';
?>
This would output:
<script>
jsvarname = new Array();
jsvarname['gdsag'] = 4;
jsvarname[0] = 'hello';
jsvarname[1] = new Array();
jsvarname[1][0] = 5;
jsvarname[1][1] = 6;
</script>
Now the array is loaded in the browser as javascript. As you can see, it supports multidimensional
arrays too.