首页 > 解决方案 > 将数据添加到 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

标签: phpjson

解决方案


您必须更改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;
    }
}

推荐阅读