[英]Why does my JSON array turn into an object?
I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process. 我正在尝试从test_bots.json取消设置一个值并将其保存回去,但是在此过程中以某种方式更改了数据格式。
test_bots.json contains this JSON array: test_bots.json包含以下JSON数组:
["John","Vladimir","Toni","Joshua","Jessica"]
My code looks like this: 我的代码如下所示:
$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);
if(in_array($good, $good_arr)){
$key = array_search($good, $good_arr);
unset($good_arr[$key]);
$good_arr2 = json_encode($good_arr);
file_put_contents('test_bots.json',$good_arr2);
}
The output that's saved is: 保存的输出是:
{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}
but I want the output to look like: 但我希望输出看起来像:
["John","Vladimir","Joshua","Jessica"]
I tried to unserialize the array before saving it, but it's not working. 我在保存之前尝试对数组进行反序列化,但是它不起作用。
Why is this happening? 为什么会这样呢?
In order for json_encode
to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. 为了让
json_encode
将具有数字键的PHP数组转换为JSON数组而不是JSON对象,这些键必须是顺序的。 (See example #4 in the PHP manual for json_encode
. ) (请参阅PHP手册中的示例#4中的
json_encode
。 )
You can accomplish this in your code by using array_values
, which will reindex the array after you have removed one of the items. 您可以使用
array_values
在代码中完成此操作,该操作将在删除其中一项后重新索引数组。
$good_arr2 = json_encode(array_values($good_arr));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.