简体   繁体   English

如何将json对象从PHP转换为Javascript数组

[英]How to covert json object from PHP to Javascript array

Background Information 背景资料

I need to "pass" a javascript array to some front end logic that someone else wrote. 我需要将javascript数组“传递”给其他人编写的某些前端逻辑。 in reviewing their code, I see they are creating dummy data like this: 在查看他们的代码时,我看到他们正在创建伪数据,如下所示:

<script>
//define some sample data
 var tabledata = [
    {id:1, name:"JohnDoe", company:"Acme", email:"jdoe@acme.com", title:"CEO", regtype:"12345"},
    {id:2, name:"JaneDoe", company:"Widgets Inc", email:"janedoe@hotmail.com", title:"Programmer", regtype:"12345"}    
 ];

My logic is all the backend stuff that gets real data from a database. 我的逻辑是所有从数据库获取真实数据的后端东西。 I get back a json string that looks like this: 我返回一个看起来像这样的json字符串:

{
    "items": [{
        "id": 2089025,
        "first_name": "Devon",
        "last_name": "Ackerman"
    }, {
        "id": 2163367,
        "first_name": "Ryan",
        "last_name": "Acuff"
    }]
}

Problem 问题

I don't know the correct way to convert/cast this in PHP to make it end up as an array in Javascript. 我不知道正确的方法来在PHP中进行转换/转换以使其最终成为Javascript中的数组。

Code

This is the code I have so far in PHP that a) proves I'm getting a string b) tries to convert it to a json object. 这是我到目前为止在PHP中拥有的代码,a)证明我得到一个字符串b)尝试将其转换为json对象。

$json_obj = json_decode($response, true);
//echo json_last_error();
echo gettype($response);
echo gettype($json_obj);

The first gettype() returns "string". 第一个gettype()返回“字符串”。 The second returns "array". 第二个返回“数组”。

A few lines later, i finish the PHP section and I do this: 几行后,我完成了PHP部分,然后执行以下操作:

<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var tabledata = <?php echo ($json_obj) ?>;
console.log(typeof(tabledata))
console.log(tabledata)

I see the following in the console as the output for the two calls to console.log(): 我在控制台中看到以下内容作为对console.log()的两次调用的输出:

function
ƒ Array() { [native code] }

can someone point me in the right direction? 有人可以指出我正确的方向吗?

Thanks. 谢谢。

var tabledata = <?php echo ($json_obj) ?>;

Should be... 应该...

var tabledata = <?php echo json_encode($json_obj) ?>;

This will turn it into json, and the browser will auto parse it for you when the page loads. 这会将其转换为json,并且在页面加载时浏览器将自动为您解析。

In your case, since you already started with an encoded value, you could just use that. 在您的情况下,由于您已经开始使用编码值,因此可以使用它。

var tabledata = <?php echo $response ?>;

Or I believe PHP has a shortcut for echoing that you could also do... 或者我相信PHP具有回显的快捷方式,您也可以这样做...

var tabledata = <?= $response ?>;

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

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