I've only tested this as far as running the provided script in Firefox and making sure there aren't any errors in the Javascript console, I haven't actually tried to use the arrays/object for anything. Could you please leave some feedback on it for me as I don't think I'm going to have the chance to properly play with it before I forget about it :p Thanks.
<?php
$test_array=toJavascript(array('here', 'are some', 'values', array('and', 'extra', 'dimentions')));
$test_assoc=toJavascript(array('key'=>'value', 'is'=>'the',
'perfect'=>array('example', 'of', 'how'),
'thism'=>array('whole'=>'thing', 'works')));
echo <<<END_HTML
<script type="text/javascript">
var test_array = $test_array
var test_assoc = $test_assoc
</script>
END_HTML;
function toJavascript($var) {
if(is_array($var)) {
if(!$result=toJavascript_fromArray($var))
$result=toJavascript_fromAssoc($var);
}
return $result.';';
}
function toJavascript_fromArray($var) {
$output='new Array(';
$first=true;
foreach($var as $key => $value) {
if(!is_numeric($key) || $key!=intval($key)) return false;
if(!$first) $output.=',';
$first=false;
if(is_array($value)) {
if(!$tmp=toJavascript_fromArray($value))
$output.=toJavascript_fromAssoc($value);
else
$output.=$tmp;
} else {
$output.="'$value'";
}
}
return $output.')';
}
function toJavascript_fromAssoc($var) {
$output='{';
$first=true;
foreach($var as $key => $value) {
if(!$first) $output.=",";
$first=false;
//The key cannot have certain characters in, I'm not sure of the full list
//of these characters so I've assumed that if we strip all PCRE non word
//characters we should be OK, this may well not be the case though.
$key=preg_replace('/\W/', '', $key);
//Also, keys cannot be numeric so we add an underscore to the start.
if(is_numeric($key)) $key='a'.$key;
$output.=" $key:";
if(is_array($value)) {
if(!$tmp=toJavascript_fromArray($value))
$output.=toJavascript_fromAssoc($value);
else
$output.=$tmp;
} else {
$output.="'$value'";
}
}
return $output.' }';
}
?>
Cheers
Bubble