为每个Json元素生成带有{字符而不是[的Json


Generate Json with { character instead of [ for every json element

我正在生成一个Json文件,每个元素的分隔符是

(

我希望有

{

字符作为分隔符。不确定,但我没有接收到使用Angularjs应用程序的Ionic结果,当我使用{硬编码结果时,我确实收到了结果。我做:$result[] = json_encode($JsonElement);:

$result = array();
$JsonElement = array();
while ($row = oci_fetch_array($stid)) {
        foreach ($row as $item) {
                $JsonElement[] = $item;
        }
        $result[] = json_encode($JsonElement);
        $JsonElement = null;
        $JsonElement = array();
}
echo json_encode($result);

输出

[
        "["123","1"]",
        "["456","2"]",
        "["789","3"]"
]

我希望json使用这种格式:

[
        {"123","1"},
        {"456","2"},
        {"789","3"}
]

我从PHP到Angular的JSON数据表现很奇怪。如果您使用$http服务发送请求,则需要在其中包含headers字段:

headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
对于PHP文件,你需要正确的头文件:
header("Content-Type: application/json"); //Set header for outputing the JSON information
http_response_code(200);
echo json_encode($result, JSON_PRETTY_PRINT); //After you're done adding in all the necessary information from the while loop

你不需要"硬核"(不确定你的意思)JSON格式自己作为json_encode将照顾你。同时从循环中删除json_encode,您不需要它两次:

while ($row = oci_fetch_array($stid)) {
        foreach ($row as $item) {
                $JsonElement[] = $item;
        }
        $result[] = $JsonElement;
        $JsonElement = null;
        $JsonElement = array();
}

我对你的循环结构有点困惑,也许我错了,但我认为它应该是这样的:

while ($row = oci_fetch_array($stid)) {
    $result[] = $row;
}

我认为你在做额外的东西,以获得JSON格式正确?