Search code examples
phparraysjsonunset

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


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?


Solution

  • 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"}]