我正在尝试从 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/