3 回答
TA贡献1786条经验 获得超11个赞
这是因为你总是将$params
变量设置为一个新数组,所以它变成了一个新数组,当你这样做时,$post = json_encode($params);
你总是得到最后一个索引结果。
基本上,您应该$params
只在循环之外初始化数组。
TA贡献2019条经验 获得超9个赞
您的代码工作正常,只需更改以下两行。
1
$entries['content_no'] = data['content_no'];
到
$entries['content_no'] = $data['content_no']; //were only missing a $ variable sign
2
$post = json_encode($params);
到
$post[] = json_encode($params); //you defined an array but you were not pushing data in to the array
TA贡献1864条经验 获得超6个赞
您的代码中有一些错误(我假设 - 如果您有不同的结果,请忽略它们),但主要是您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}]}"
- 3 回答
- 0 关注
- 375 浏览
添加回答
举报