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文件读取到PHP数组,然后回显数组的内容,所以我可以用javascript中的ajax获取信息,并将javascript中的数组转换为JSON对象数组。
Here is how my JSON file looks like.
这是我的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\"}"]]
Here is my php :
这是我的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"}
It looks like I am not that far, but what can I do so I can actually make this a JSON object?
看起来我不是那么远,但是我能做什么才能让它成为JSON对象呢?
Please help!
1 个解决方案
#1
1
The problem is that you have JSON inside JSON.
问题是你在JSON中有JSON。
you have to decode twice:
你必须解码两次:
<?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);
gives me this:
给我这个:
[{
"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"
}]
which is valid JSON itself and probably what you want.
这是有效的JSON本身,可能你想要的。
#1
1
The problem is that you have JSON inside JSON.
问题是你在JSON中有JSON。
you have to decode twice:
你必须解码两次:
<?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);
gives me this:
给我这个:
[{
"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"
}]
which is valid JSON itself and probably what you want.
这是有效的JSON本身,可能你想要的。