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条)

相关推荐 更多相似问题