dongou1970 2018-06-08 12:24
浏览 64
已采纳

如何使用PHP在JSON对象中正确创建和附加数据?

I'm struggling on how to properly create a JSON file and append data to it, here's my PHP code:

<?php 

$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];

//Load the file
$jsonStr = file_get_contents($jsonFile);

//Decode the JSON data into a PHP array.
$array = json_decode($jsonStr, true);

if ($array != null) {
    $arrNew['ObjID']++;
    $arrNew['username'] = $username;
    $arrNew['email'] = $email;

    array_push($array, $arrNew);

} else {
    $arrNew = [];
    $array['ObjID'] = 0;
    $array['username'] = $username;
    $array['email'] = $email;

    array_push($array, $arrNew);
} 

// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);

// echo data
echo $jsonData;
?> 

If I refresh the URL in my browser by calling my php file, I get this output if i go to example.com/_users.json

{
  "0": [], 
  "1": {
    "ObjID": 1,
    "username": "bob",
    "email": "b@doe.com"
  },
  "2": {
    "ObjID": 1,
    "username": "sarah",
    "email": "b@doe.com"
  },
  "3": {
    "ObjID": 1,
    "username": "sarah",
    "email": "b@doe.com"
  },
  "ObjID": 0,
  "username": "bob",
  "email": "b@doe.com"
}

So I'm able to generate a .json file, but what I need to do is a piece of code to do the following sequence:

  1. Since the first time I run the script, the _users.json file doesn't exist, it needs to get generated
  2. Create a JSON main object
  3. Insert 1st object inside the main object
  4. Append a 2nd object (still inside the main object)
  5. And so on with 3rd, 4th, etc..

So I would need to get an output like this:

{ <-- Main Object starts

  "1": { <-- 1st object inside the Main Object
    "ObjID": 1,
    "username": "bob",
    "email": "b@doe.com"
  },
  "2": { <-- 2nd object
    "ObjID": 1,
    "username": "sarah",
    "email": "s@doe.com"
  }

} <-- Main Object closes

I can't really figure out what I'm doing wrong in my PHP code.

  • 写回答

2条回答 默认 最新

  • douzao2992 2018-06-08 12:27
    关注

    Logic in the else part should be inverted:

    } else {
      $array = [];
      $arrNew['ObjID'] = 0;
      $arrNew['username'] = $username;
      $arrNew['email'] = $email;
    
      array_push($array, $arrNew);
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装