我想从数组中删除一个元素(从json转换而来),但使用unset并在json中重新转换,数组就会变为索引。
源阵列:
{"rows":
[{"c":[{"v":"Date(1409052482000)"},{"v":22},{"v":22},{"v":22},{"v":null}]},
{"c":[{"v":"Date(1409052614000)"},{"v":22},{"v":22},{"v":22},{"v":null}]},
{"c":[{"v":"Date(1409052782000)"},{"v":22},{"v":22},{"v":22},{"v":null}]}
]}
结果:
{"rows":
"2":{"c":[{"v":"Date(1409052614000)"},{"v":22},{"v":22},{"v":22},{"v":null}]},
"3":{"c":[{"v":"Date(1409052782000)"},{"v":22},{"v":22},{"v":22},{"v":null}]}
}}
问题出在"2"answers"3"键上。我不想要这个键,因为我使用谷歌图表的数据,并且对于这个索引键是合理的。
PHP代码:
$tempdata = json_decode($jsonTempLog, TRUE);
foreach ($tempdata['rows'] as $key => $row) {
if ( $logtime < $showtime) {
unset($tempdata['rows'][$key]);
}
}
echo json_encode($tempdata);
如何从数组中删除元素,保持原始json语法?
只需执行以下操作:
$tempdata["rows"] = array_values($tempdata["rows"]);
echo json_encode($tempdata);
否则,JSON会认为您发送的是一个关联数组,而不是一个数字数组
这就是我使用的方式
unset($infos[$i]);
$infos = array_values($infos);
可能是这样的:
foreach($tempdata as $row){
$tempdata[$rows['keyfield']] = $row;
}