我正在尝试从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对象吗?
请帮忙!
答案 0 :(得分:1)
问题是你在 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本身,也可能是你想要的。