JSON 响应仅转储一个结果而不是三个结果。
我需要以以下 json 格式获取 json 响应。 它包含三个结果
{"entries":[{"id":"1A","content_no":101},
{"id":"1B","content_no":102},
{"id":"1C","content_no":103}
]}
当我按照 json 结果运行下面的代码时:
// curl result
//echo $result;
$json = json_decode($result, true);
// initial post variable
$post= [];
foreach($json['entries'] as $data){
// printed three result successfilly in for each loop
$id = $data['id'];
$content_no = $data['content_no'];
// Now to get the result in the required json format and dump it or echo it outside for each loop
$entries = array();
$entries['id'] = $data['id'];
$entries['content_no'] = data['content_no'];
$params = array();
$params['entries'][] = $entries;
$post = json_encode($params);
}
// send post result in json format to database
var_dump($post);
for each 循环打印 3 个结果,但我的问题是只有一个结果按照下面的 json 转储 var。我想知道其他 2 个结果藏在哪里。请问我如何按照上面的 JSON 格式获得剩余的 2 个结果
{"entries":[{"id":"1C","content_no":103}]}
这是因为您总是将$params
变量设置为新数组,因此它会变成一个新数组,当您这样做时$post = json_encode($params);
您总是得到最后一个索引结果。
基本上,您应该仅在循环外初始化$params
数组。
您的代码中有一些错误(我假设 - 如果您有不同的结果,请忽略它们(,但最主要的是您在循环中json_encode()
值,而不是构建数据列表然后对其进行编码(代码中错误的更改注释(...
$json = json_decode($result, true);
$post= [];
foreach($json['entries'] as $data){ // Change from $json_result
// printed three result successfilly in for each loop
$id = $data['id'];
$content_no = $data['content_no'];
// Now to get the result in the required json format and dump it or echo it outside for each loop
$entries = array();
$entries['id'] = $data['id'];
$entries['content_no'] = $data['content_no']; // Change from data['content_no'];
$post['entries'][] = $entries; // Just add new data to $post instead
}
// Encode total of all data
$post = json_encode($post);
var_dump($post);
给。。。
string(100) "{"entries":[{"id":"1A","content_no":101},
{"id":"1B","content_no":102},
{"id":"1C","content_no":103}]}"
你"干净"你的post
总是在循环中,只需更新它。
<?php
// curl result
//echo $result;
$json = json_decode($result, true);
// initial post variable
$post= [];
foreach($json['entries'] as $data){
// printed three result successfilly in for each loop
$id = $data['id'];
$content_no = $data['content_no'];
// Now to get the result in the required json format and dump it or echo it outside for each loop
$entries = array();
$entries['id'] = $data['id'];
$entries['content_no'] = data['content_no'];
$post['entries'][] = $entries;
}
// send post result in json format to database
var_dump($post);
您的代码工作正常,只需更改以下两行即可。
1
$entries['content_no'] = data['content_no'];
自
$entries['content_no'] = $data['content_no']; //were only missing a $ variable sign
阿拉伯数字
$post = json_encode($params);
自
$post[] = json_encode($params); //you defined an array but you were not pushing data in to the array