Convert php array to Javascript
Dumb and simple :
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
Spudley's answer is fine.
Security Notice: The following should not be necessary any longer for you
If you don't have PHP 5.2 you can use something like this:
function js_str($s)
{
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array)
{
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
echo 'var cities = ', js_array($php_cities_array), ';';
You do not have to call parseJSON since the output of json_encode
is a javascript literal. Just assign it to a js variable.
<script type="text/javascript">
//Assign php generated json to JavaScript variable
var tempArray = <?php echo json_encode($php_array); ?>;
//You will be able to access the properties as
alert(tempArray[0].Key);
</script>
I'm going to assume that the two arrays you've given for PHP and JS are not related, and they're just examples of how arrays look in the two languages. Clearly you're not going to be able to convert those sequences of letters and numbers into those city names.
PHP provides a function to convert PHP arrays into Javascript code: json_encode()
. (technically, it's JSON format; JSON stands for JavaScript Object Notation)
Use it like this:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
See also the manual page I linked above for more information.
Note that json_encode()
is only available in PHP 5.2 and up, so if you're using an older version, you'll need to use an existing one -- the PHP manual page also includes comments with functions written by people who needed it. (but that said, if you're using anything older than PHP 5.2 you should upgrade ASAP)