简体   繁体   English

将对象的php数组转换为javascript数组

[英]Convert php array of objects to javascript array

if i have an associative array in php. 如果我在php中有一个关联数组。

Say, in the same view, i have $params array: 说,在同一视图中,我有$ params数组:

$parameters = array(
   'parameter1'=>'value1',
   'parameter2'=>'value2
);

Is there any way or php function or even javascript function to convert the php array to javascript array? 有什么方法或PHP函数甚至JavaScript函数将php数组转换为javascript数组吗? in such a way that if we have the converted array, jsParameters , you'd be able to access it's fields and values like : 这样,如果我们拥有转换后的数组jsParameters ,则可以访问它的字段和值,例如:

console.log(jsParameters.parameter1);
console.log(jsParameters.parameter2);

that will output, 'value1' and 'value2'. 将会输出“ value1”和“ value2”。 Is there a way? 有办法吗? many Thanks! 非常感谢!

使用json_encode

console.log(<?php echo json_encode($parameters); ?>);

使用json_encode

echo json_encode($parameters);

You should be able to call json_encode on the array, and echo that back to your application. 您应该能够在数组上调用json_encode ,并将其回显给您的应用程序。

Check out the docs here 这里查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM