【问题标题】:How to remove first two JSON objects from JSON file using PHP如何使用 PHP 从 JSON 文件中删除前两个 JSON 对象
【发布时间】:2014-10-15 17:25:14
【问题描述】:

我有一个名为“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"}
]

我该怎么做?

【问题讨论】:

  • 我会使用file_get_contentsfile_put_contentsjson_decodejson_encode 和一些unset。你能自己试一试吗?这是很好的做法。

标签: php arrays json unset


【解决方案1】:

试试这个:

<?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】:

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

    相反,读取文件,解析 json,使用 array_shift() 或类似的东西来删除数组中的前两个元素,将生成的数组编码为 json 并将其放回文件中。

    【讨论】:

      【解决方案3】:

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

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

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 2018-10-14
        • 2021-08-10
        • 2020-10-15
        • 2021-09-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多