将数据添加到JSON子数组

时间:2019-05-21 10:40:11

标签: php json

这是我的JSON文件(database.json):

{
  "doctors": [
    {
      "ID": "ahmadakhavan",
      "pass": "1234",
      "name": "Ahmad Akhavan",
      "profilePic": "address",
    },
    {
      "ID": "akramparand",
      "pass": "1234",
      "name": "Akram Parand",
      "profilePic": "address",
    }
  ],
  "games": [
    {
      "ID": "shuttlefuel_1",
      "locked": "0",
      "logo": "gameLogo",
    },
    {
      "ID": "birthdaycake",
      "locked": "0",
      "logo": "gameLogo",
    }
  ],
  "users": [
    {
      "ID": "alirezapir",
      "prescribes": [
        {
          "doctorName": "doctor1",
          "done": "yes",
          "gameId": "wordschain"
        },
        {
          "doctorName": "doctor2",
          "done": "no",
          "gameId": "numberlab"
        }
      ],
      "profilePic": "address"
    },
    {
      "ID": "amirdibaei",
      "pass": "1234",
      "profilePic": "address"
    }
  ]
}

我想在prescribes数组下添加一个用于特定ID的孩子。

以下是我在PHP代码中所做的操作:

 <?php 
  $username = $_REQUEST['name'];
  $data = $_REQUEST['data'];

  //Load the file
 $contents = file_get_contents('./database.json');
  $arraydata = json_decode($data,true);
 //Decode the JSON data into a PHP array.
 $contentsDecoded = json_decode($contents, true );
     foreach($contentsDecoded['users'] as $item){
         if($item['ID'] == $username){
             if(!isset($item['prescribes'])){
                 $item['prescribes'] = Array();
             }
             array_push($item['prescribes'],$arraydata);
            $json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
            file_put_contents('./database.json', $json);  
             exit('1');
             exit;
         }
     }
    exit('0'); 
    exit;
 ?> 

如果我在$item['prescribes']行之后回显array_push($item['prescribes'],$arraydata);,则看到已添加数据,但是原始文件(database.json)将不会显示新添加的数据。

(表示此新数据未添加到$contentsDecoded

2 个答案:

答案 0 :(得分:1)

您必须像下面这样更改foreach()代码:-

foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
    if($item['ID'] == $username){
        $item['prescribes'][] = $arraydata; //assign new value directly
        $json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
        file_put_contents('./database.json', $json);  
        exit;
    }
}

答案 1 :(得分:1)

更改您的foreach以更改$ contentsDecoded数组:

foreach($contentsDecoded['users'] as $key => $item){
         if($item['ID'] == $username){
             if(!isset($item['prescribes'])){
                 $contentsDecoded['users'][$key]['prescribes'] = Array();
             }
             array_push($contentsDecoded['users'][$key]['prescribes'],$arraydata);
            $json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
            file_put_contents('./database.json', $json);  
             exit('1');
             exit;
         }
     }