如何使用PHP从JSON文件中删除前两个JSON对象

如何使用PHP从JSON文件中删除前两个JSON对象,php,arrays,json,unset,Php,Arrays,Json,Unset,我有一个名为“jason_file.JSON”的JSON文件,看起来像: [ {"name":"name1", "city":"city1", "country":"country1"}, {"name":"name2", "city":"city2", "country":"country2"}, {"name":"name3", "city":"city3", "country":"country3"}, {"name":"name4", "city":"city4", "count

我有一个名为“jason_file.JSON”的JSON文件,看起来像:

[
 {"name":"name1", "city":"city1", "country":"country1"},
 {"name":"name2", "city":"city2", "country":"country2"},
 {"name":"name3", "city":"city3", "country":"country3"},
 {"name":"name4", "city":"city4", "country":"country4"},
 {"name":"name5", "city":"city5", "country":"country5"}
]
使用for循环,我想从文件中删除前两个对象,并将其余对象以相同的顺序保存在“jason_file.json”中。要求的结果应为:

[
 {"name":"name3", "city":"city3", "country":"country3"},
 {"name":"name4", "city":"city4", "country":"country4"},
 {"name":"name5", "city":"city5", "country":"country5"}
]

我该怎么做呢?

为了确保最终得到有效的json,我不会手动编辑该文件

相反,读取文件,解析json,使用
array\u shift()
或类似方法删除数组中的前两个元素,将生成的数组编码为json并将其放回文件中。

尝试以下操作:

<?php

$json = '[
 {"name":"name1", "city":"city1", "country":"country1"},
 {"name":"name2", "city":"city2", "country":"country2"},
 {"name":"name3", "city":"city3", "country":"country3"},
 {"name":"name4", "city":"city4", "country":"country4"},
 {"name":"name5", "city":"city5", "country":"country5"}
]'; //file_get_contents('jason_file.json');

$json = json_encode(array_slice(json_decode($json, true), 2));
/*                              (1) decode the JSON string
                    <-----------
                    (2) cut off the first two elements
        <-----------
        (3) recode as JSON
*/

echo $json;

//file_put_contents('jason_file.json, $json);

首先,您需要将文件拉入字符串。所以

$str = file_get_contents('/path/to/my/file');
然后,您将需要解码字符串内容

$arr = json_decode($str, true);
最后将数组移动两次

$arr = array_shift($arr);
$arr = array_shift($arr);
或者,对数组进行切片

$arr = array_slice($arr, 2);
最后,您可以将json字符串放回文件中

$newJson = json_encode($arr);
file_put_contents('/path/to/saved/file', $newJson);

希望这有帮助

我会使用
file\u get\u contents
file\u put\u contents
json\u decode
json\u encode
和一些
unset
。你能自己试一试吗?这是很好的练习。
$newJson = json_encode($arr);
file_put_contents('/path/to/saved/file', $newJson);