无法使用php从JSON文件正确读取 [英] Unable to read properly from JSON file with php
问题描述
我正在尝试从JSON文件读取到PHP数组中,然后回显该数组的内容,因此我可以使用javascript中的ajax
获取信息,并将javascript中的数组转换为JSON对象数组.
I am trying to read from a JSON file into a PHP array and then echo the array's content, so I can fetch the info with ajax
in javascript and convert the array in javascript to an array of JSON objects.
这是我的JSON文件的样子.
Here is how my JSON file looks like.
[["{\"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;
}
?>
这就是我在客户端得到的:
And this is what I am getting on the client side :
{"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对象呢?
It looks like I am not that far, but what can I do so I can actually make this a JSON object?
请帮助!
推荐答案
问题是您的JSON 内部 JSON.
The problem is that you have JSON inside 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本身,也可能是您想要的.
which is valid JSON itself and probably what you want.
这篇关于无法使用php从JSON文件正确读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!