0

I have a .json file and I want to append an object to a vector in the file, but I got some errors.

            $json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
            $jsonarray = json_decode($json, true);

            $myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
            $myObj->title = $_POST["title"];
            $myObj->description = $_POST["description"];
            $myObj->cover = "";
            $myObj->VR = false;
            $myObj->slow = false;
            $td = '2D';
            $myObj->$td = false;
            $fd = '3D';
            $myObj->$fd = false;
            if($_POST["isprivate"]){
                $myObj->license = "nonfree";
            } else {
                $myObj->license = "free";
            }
            $myObj->lang = "en";
            $id = count($jsonarray['packages'])+1;
            $myObj->id = $id;
            $myObj->soon = false;
            $myObj->date = $_POST["date"];
            $myObj->creator = $_POST["creator"];
            $myObj->creator_institution = $_POST["creator_institution"];
            $myObj->keywords = $_POST["keywords"];
            $myObj->data = $_POST["data"];

            $myJSON = json_encode($myObj);
            echo $myJSON;
            array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
            $jsondata = json_encode($jsonarray, true);

            $myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
            if(file_put_contents($myFile, $jsondata)) {
                echo 'Data successfully saved';
            } else 
                echo "error";

And when I try to save it then It is saved, but without the modifications, without the new object, but where I echo $myJSON there the object seems good.

Here is an example of my .json file:

{
  "description": "some description",
  "creators": [
    {
      "name": "cname",
      "whoishe": "cv",
      "avatar": "",
      "id": 123
    }
  ],
  "lang": "en",
  "materialname": "mat name",
  "generalmaterialid": "mat_id",
  "thismaterialid": "this_mat_id",
  "packages": [
    {
      "short": "pack short desc",
      "title": "pack title",
      "description": "pack long desc",
      "cover": "pack cover",
      "VR": true,
      "slow": true,
      "2D": true,
      "3D": true,
      "license": "free",
      "lang": "en",
      "id": 1,
      "soon": false
    }
  ]
}

I have been inspired from here: https://www.w3schools.com/js/js_json_php.asp and here http://www.kodecrash.com/javascript/read-write-json-file-using-php/.

What have I done wrong here? How can I resolve it? What is the correct version in this case? Thanks for any help!

gabor aron
  • 390
  • 2
  • 3
  • 15
  • 1
    http://php.net/manual/en/function.array-push.php - the first argument to array_push should be the array you want to push onto. The second argument should be the value to push. You just got them the wrong way round. This is effectively what the warning is trying to tell you. Always pays to just quickly check the documentation. – ADyson Jul 30 '18 at 10:15
  • @ADyson than how can I push this object to `json`? this isn't an array, or am I wrong? – gabor aron Jul 30 '18 at 10:20
  • @ADyson and what about the first warning? – gabor aron Jul 30 '18 at 10:22
  • So did you read the link I provided? You just need to swap the arguments to array_push. `array_push($jsonarray['packages'], $myJSON);` The documentation makes it very clear that the array you want to push the data into has to be the _first_ argument into the function. – ADyson Jul 30 '18 at 10:29
  • As for the first warning, you know you can google the text of warnings and errors? You're rarely the first person to encounter it. First result on google is https://stackoverflow.com/questions/8900701/creating-default-object-from-empty-value-in-php, you can get some big clues from there. Correct me if I'm wrong but the main problem you appear to be suffering from here is a simple lack of basic research and reading. – ADyson Jul 30 '18 at 10:30
  • @ADyson thank you, but you are wrong, as you see the links in my question, I searched for this, and there these things worked well, but, this doesn't resolve my problem. This appends the JSON with a string, not with an object... – gabor aron Jul 30 '18 at 10:55
  • well that's not very surprising, since `$myJSON` _is_ a string...you specifically encoded it into a string using json_encode(). If you want to append a PHP object, then append a PHP object, such as, maybe, $myObj for instance. P.S. The links in your question are not links which would explain the warnings you're asking about. My point was you can research the warnings themselves. – ADyson Jul 30 '18 at 10:55
  • @ADyson than answer it and then I can accept your answer – gabor aron Jul 30 '18 at 11:30

1 Answers1

0

Firstly, you've got your arguments to array_push() back to front. The array you want to insert into has to be the first argument you give to the function.

Secondly, you're appending a JSON string ($myJSON) to the array, instead of your object data. This doesn't work because when you later come to encode the whole array as JSON, the bit that's already a JSON string is simply treated as a string, and ends up being double-encoded. You need to push the actual PHP object to the array. It will be encoded later when everything else is.

So

$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);

can become simply

array_push($jsonarray['packages'], $myObj);

P.S. You can also remove the warning about "Creating default object from empty value" by writing

$myObj = new \stdClass();

just before the line

$myObj->short = $_POST["short"];

so that you're adding your properties to an object which already exists.

ADyson
  • 57,178
  • 14
  • 51
  • 63