Das PHP-Array:
Array ( [bar] => one [0] => Array ( [0] => a [1] => b [2] => Array ( [0] => c [1] => d [2] => 9.2 ) [3] => e [4] => 1 ) )
var myJsArray = new Array(); myJsArray["bar"] = "one"; myJsArray[0] = new Array(); myJsArray[0][0] = "a"; myJsArray[0][1] = "b"; myJsArray[0][2] = new Array(); myJsArray[0][2][0] = "c"; myJsArray[0][2][1] = "d"; myJsArray[0][2][2] = 9.2; myJsArray[0][3] = "e"; myJsArray[0][4] = 1;
<?php
$myPhpArray = array('bar' => 'one', array('a', 'b', array('c', 'd', 9.2), 'e', 1));
/*
php2js -- Converts a PHP-array to a JavaScript-array
php2js([array php [, string name [, bool useVar]]])
This function convert a PHP-array to a JavaScript-array by preserving its structure.
If php is not an array, an error will be thrown and the executions of the script stopped.
If no array is passed to the function, an empty array will be used instead.
The parameter name represents the name of the created JavaScript-Array. By default, it's
'foo'. If the last parameter useVar is TRUE, the var-statement will be printet in front
of the root element of the array like this:
var foo = new Array();
By that you can change the scope of the array. Default is TRUE.
If a key or a value of an element in the array is numeric, it will be numeric in
JavaScript, too. Otherwise double quotes are used as string delimiters.
Version 1.0 by David Tibbe, 2004/10/18
*/
function php2js($php = array(), $name = 'foo', $useVar = TRUE) {
if (!is_array($php)) {
trigger_error('The frist parameter has to be an array', E_USER_ERROR);
die();
}
static $first = TRUE;
if ($first) {
if ($useVar) { echo 'var '; }
echo $name.' = '; $first = FALSE;
}
echo "new Array();\n";
foreach ($php as $key => $value) {
$OName = $name.'[';
if (is_numeric($key)) {
$OName .= $key;
} else {
$OName .= '"'.$key.'"';
}
$OName .= ']';
echo $OName.' = ';
if (is_array($value)) {
php2js($value, $OName, FALSE);
} else {
if (is_numeric($value)) {
echo $value;
} else {
echo '"'.$value.'"';
}
echo ";\n";
}
}
}
echo 'Das PHP-Array:<pre>';
print_r($myPhpArray);
echo '</pre><hr>Das JS-Array:<pre>';
php2js($myPhpArray, 'myJsArray');
echo '</pre><hr />';
highlight_file(__FILE__);
?>