How to remove first two JSON objects from JSON file using PHP

心不动则不痛 提交于 2019-12-25 03:28:08

问题


I have a JSON file named 'jason_file.json' that is look like:

[
 {"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"}
]

Using for loop, I want to remove first two objects from file and save remaining objects in the same order in the 'jason_file.json'. Required result should be:

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

How can I do it?


回答1:


Try this:

<?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);

Output:

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



回答2:


To make sure you end up with valid json, I would not edit the file manually.

Instead, read the file, parse the json, use array_shift() or something similar to remove the first two elements in the array, encode the resulting array as json and put it back in the file.




回答3:


Well firstly, you will want to pull the file into a string. So

$str = file_get_contents('/path/to/my/file');

Then you will want to decode the string contents.

$arr = json_decode($str, true);

Finally shift the array twice

$arr = array_shift($arr);
$arr = array_shift($arr);

Or alternatively, slice the array

$arr = array_slice($arr, 2);

Finally, you can place the json string back into a file.

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

Hope this helps!



来源:https://stackoverflow.com/questions/25437158/how-to-remove-first-two-json-objects-from-json-file-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!