如何使用PHP编辑JSON?

时间:2019-06-25 05:22:09

标签: php json

<?php
global $obj;
global $books;
global $chapters;
global $verses;
global $newObj;

 $json = file_get_contents("json/jsoneng.json");
 $obj = json_decode($json, true);

 foreach($obj['books'] as $books){
     foreach ($books['chapters'] as $chapters){
         foreach($chapters['verses'] as $verses){

             echo $verses['text'] . "<br/>";
              $verses['text'] = "";      
            }
     }
 }


 $newObj = json_encode($obj);
 file_put_contents('json/what.json', $newObj);

?>

这就是我的JSON的样子:

{
    "books": [
        {
            "book": "1 Nephi",
            "chapters": [
                {
                    "chapter": 1,
                    "reference": "1 Nephi 1",
                    "verses": [
                        {
                            "reference": "1 Nephi 1:1",
                            "text": "I, Nephi, having been born of goodly parents, therefore I was taught somewhat in all the learning of my father; and having seen many afflictions in the course of my days, nevertheless, having been highly favored of the Lord in all my days; yea, having had a great knowledge of the goodness and the mysteries of God, therefore I make a record of my proceedings in my days.",
                            "verse": 1
                        },
                        {
                            "reference": "1 Nephi 1:2",
                            "text": "Yea, I make a record in the language of my father, which consists of the learning of the Jews and the language of the Egyptians.",
                            "verse": 2
                        },
                        {
                            "reference": "1 Nephi 1:3",
                            "text": "And I know that the record which I make is true; and I make it with mine own hand; and I make it according to my knowledge.",
                            "verse": 3
                        },

............................................

我想删除整个文本并将其设为空白 “ text”:“”,

但是我的代码不起作用,它正在保存相同的原始json文件。

2 个答案:

答案 0 :(得分:3)

您必须通过&引用使用通行证

foreach($chapters['verses'] as &$verses){
   $verses['text'] = "";      
}

您的代码应为:-

foreach($obj['books'] as &$books){
   foreach ($books['chapters'] as &$chapters){
     foreach($chapters['verses'] as &$verses){
          $verses['text'] = "";      
        }
   }
 }

Working example

答案 1 :(得分:2)

您必须使用passing by reference concept of php

案例1: 如果每种情况下json结构始终相同,则

foreach($obj['books'][0]['chapters'][0]['verses'] as &$verses){//& => passing by reference concept
  $verses['text'] = '';
}

输出:-https://3v4l.org/sOEuV

情况2: 如果json结构可以更改,则

foreach($obj['books'] as &$books){
     foreach ($books['chapters'] as &$chapters){
         foreach($chapters['verses'] as &$verses){ //& => passing by reference concept
            $verses['text'] = "";      
         }
     }
}

输出:-https://3v4l.org/1Uv5Y