|
// 支持变量类型:
// int double string array object
// 例:
// $arr = array(
// 'key1' => 'value1',
// 'key2' => 'value2',
// 'key3' => 2334,
// 'key'4 => array(1,2,3)
// );
// php2js($arr);
// php2js_assign 函数生成一个赋值表达式而不新声明一个js变量
function php2js_assign($js_name,$js_value)
{
switch(gettype($js_value))
{
case "string":
$js = "{$js_name} = '{$js_value}';\r\n";
break;
case "double":
case "integer":
$js = "{$js_name} = {$js_value};\r\n";
break;
case "boolean":
if($js_value) $js = "{$js_name} = true;\r\n"; else $js = "{$js_name} = false;\r\n";
break;
case "array":
$js = "{$js_name} = new Array();\r\n";
foreach($js_value as $key => $value)
{
$sub_name = $js_name."['{$key}']";
$js .= php2js_assign($sub_name,$value);
}
break;
case "object":
$js = "{$js_name} = {};\r\n";
$vars = get_object_vars($js_value);
foreach($vars as $key => $value)
{
$sub_name = $js_name."['{$key}']";
$js .= php2js_assign($sub_name,$value);
}
break;
case "NULL":
$js = "{$js_name} = null;\r\n";
break;
default:
break;
}
return $js;
}
function php2js($js_name,$js_value)
{
return "var ".php2js_assign($js_name,$js_value);
} |
|