【问题标题】:Unable to read properly from JSON file with php无法使用 php 从 JSON 文件中正确读取
【发布时间】:2017-01-31 02:05:01
【问题描述】:

我正在尝试从 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-strings 并不会反过来给你一个有效的 json 字符串。您是否尝试过为此使用json_encode
  • 只用echo "[".implode(",", $arr)."]";
  • 是的,我尝试使用 json_encode,@FranzGleichmann。它给了我这样的结果(是的,它没有右方括号): ["{\"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\"}" ]{"id":1474541876849,"name":"D","price":"12"}{"id":1474541880521,"name":"DD","price":"12"}{"id ":1474541897705,"name":"DDDGG","price":"124"}

标签: javascript php arrays json ajax


【解决方案1】:

问题是你有 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 本身,可能是您想要的。

【讨论】:

  • 维伦,维伦丹克!! :))
猜你喜欢
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2018-03-21
相关资源
最近更新 更多