如何使用PHP从JSON文件中删除前两个JSON对象 [英] How to remove first two JSON objects from JSON file using PHP

查看:136
本文介绍了如何使用PHP从JSON文件中删除前两个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为'jason_file.json'的JSON文件,如下所示:

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

使用循环,我想从文件中删除前两个对象,并以相同的顺序保存其余对象'jason_file.json'。所需结果应为:

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

我该怎么办?

推荐答案

尝试一下:

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

输出

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

这篇关于如何使用PHP从JSON文件中删除前两个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆