如何使用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.

Logic in the else part should be inverted:

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

  array_push($array, $arrNew);
} 

Try below code.

$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.
if($jsonStr=='') $array = array();
else $array = json_decode($jsonStr, true);

if (empty($array)) {
$arrNew = [];
$arrNew['ObjID']=0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;

array_push($array, $arrNew);

} else {

$array['ObjID'] ++;
$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;
?>