javascript - 无法使用 php 正确读取 JSON 文件

标签 javascript php arrays json ajax

我正在尝试从 JSON 文件读取到 PHP 数组,然后回显数组的内容,这样我就可以在 javascript 中使用 ajax 获取信息,并将 javascript 中的数组转换为数组JSON 对象。

这是我的 JSON 文件的样子。

[["{\"id\":1474541876849,\"name\":\"D\",\"price\":\"12\"}"],["{\"id\":1474541880521,\"name\":\"DD\",\"price\":\"12\"}"],["{\"id\":1474541897705,\"name\":\"DDDGG\",\"price\":\"124\"}"],["{\"id\":1474541901141,\"name\":\"FAF\",\"price\":\"124\"}"],["{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]]

这是我的 php :

<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true);

$arr = array();
foreach ($json_a as $key) {
    array_push($arr,$key[0]);


}
foreach ($arr as $key) {
    echo $key;
}
?>

这就是我在客户端得到的:

{"id":1474541876849,"name":"D","price":"12"}{"id":1474541880521,"name":"DD","price":"12"}{"id":1474541897705,"name":"DDDGG","price":"124"}{"id":1474541901141,"name":"FAF","price":"124"}{"id":1474543958238,"name":"tset","price":"6"}

看起来我还没有那么远,但是我能做什么才能真正将其变成一个 JSON 对象?

请帮忙!

最佳答案

问题是 JSON里面 JSON。

你必须解码两次:

<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true); //here you turn a JSON-string into an array containing JSON-strings

$arr = array();
foreach ($json_a as $key) {
    array_push($arr,json_decode($key[0],true)); //and here you turn each of those JSON-strings into objects themselves


}

echo json_encode($arr);

给了我这个:

[{
    "id": 1474541876849,
    "name": "D",
    "price": "12"
}, {
    "id": 1474541880521,
    "name": "DD",
    "price": "12"
}, {
    "id": 1474541897705,
    "name": "DDDGG",
    "price": "124"
}, {
    "id": 1474541901141,
    "name": "FAF",
    "price": "124"
}, {
    "id": 1474543958238,
    "name": "tset",
    "price": "6"
}]

这是有效的 JSON 本身,并且可能是您想要的。

关于javascript - 无法使用 php 正确读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39639979/

相关文章:

JavaScript promise : a problem with setTimeout inside a promise race

javascript - 尝试将自定义输入发送到 braintree 但只有 payment_method_nonce 有效

c++ - 大文件中的 C++ 文件读取错误

javascript - 将 .aspx 文件放入不同的文件夹后,ScriptManager.RegisterStartupScript() 不起作用

javascript - Angular.js - 重定向不起作用

php - 当文件作为 TEXT 而不是 blob 存储在 mysql 表中时,如何从 php 下载文件?

php - cakephp 按不同分组

python - 将(标量)函数数组转换为返回数组的函数

javascript - 如何抓取将所有交互都作为回发进行的 ASP.NET 站点?

php - 如何使用关联数组编写良好的 PHP 数据库插入