0

This is a little more specific than the other answers I've found or could come up with on my own.

My json file contains exactly

[ "box", "tube" ]

Nothing more and nothing less. With the json data formatted like this, I can get the exact results needed.

What I would like to do is be able to append more to the json file using PHP. I have seen:

<?php
    session_start();
    if(isset($_POST['add'])){
        $data = file_get_contents('members.json');
        $data_array = json_decode($data);
        //data in our POST
        $input = array(
            'id' => $_POST['id'],
            'firstname' => $_POST['firstname'],
            'lastname' => $_POST['lastname'],
            'address' => $_POST['address'],
            'gender' => $_POST['gender']
        );
        //append the POST data
        $data_array[] = $input;
        //return to json and put contents to our file
        $data_array = json_encode($data_array, JSON_PRETTY_PRINT);
        file_put_contents('members.json', $data_array);
        $_SESSION['message'] = 'Data successfully appended';
    }
    else{
        $_SESSION['message'] = 'Fill up add form first';
    }
    header('location:index.php');
?>

My issue with this is that I don't understand how to use this example in my case since my json data is not using a key for its single array. Do I just have to give up and find a way to use named keys to get the results I want, or is there a way to keep my json data formatted the way I want and also be able to append more data to it?

  • Out of interest. Why not use a database? – Jonnix Mar 20 '19 at 16:25
  • 1
    Ok ask yourself this, if you do just add stuff to that array `[ "box", "tube" ]` how will you know what info is what later on when you come to use it – RiggsFolly Mar 20 '19 at 16:27
  • It's such a small amount of data and seems easier to me to use a json file that I can manually enter or remove data whenever I like. Of course, I'm no pro, so I may be very wrong. Maybe a database would be easier? I would need to make a whole table just for this. Maybe that wouldn't be so bad though? –  Mar 20 '19 at 16:28
  • @RiggsFolly I don't need to know what's what in there. It's just for a drop down menu all the users use to easily input data into the field instead of typing it all out. –  Mar 20 '19 at 16:29
  • "a whole table" is actually not a lot of effort, but ok – ADyson Mar 20 '19 at 16:29
  • 1
    You don't even need a server to run. SQLite would probably fill your needs. – Jonnix Mar 20 '19 at 16:30

3 Answers3

0

If you really believe this is what you want then is this any good to you

<?php
    session_start();
    if(isset($_POST['add'])){
        $data = file_get_contents('members.json');
        $data_array = json_decode($data);
        //data in our POST

        $data_array[] = $_POST['id'];
        $data_array[] = $_POST['firstname'];
        $data_array[] = $_POST['lastname'];
        $data_array[] = $_POST['address'];
        $data_array[] = $_POST['gender'];

        $data_array = json_encode($data_array, JSON_PRETTY_PRINT);

        file_put_contents('members.json', $data_array);
        $_SESSION['message'] = 'Data successfully appended';
    }
    else{
        $_SESSION['message'] = 'Fill up add form first';
    }
    header('location:index.php');
?>

You could sexy that up a bit assuming you want all the data items from $_POST like this.

<?php
    session_start();
    if(isset($_POST['add'])){
        $data = file_get_contents('members.json');
        $data_array = json_decode($data);
        //data in our POST

        foreach ($_POST as $v) {
            $data_array[] = $v;
        }

        $data_array = json_encode($data_array, JSON_PRETTY_PRINT);

        file_put_contents('members.json', $data_array);
        $_SESSION['message'] = 'Data successfully appended';
    }
    else{
        $_SESSION['message'] = 'Fill up add form first';
    }
    header('location:index.php');
?>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • That gets me exactly what I was looking for. It seems like the simplest solution to do it the way I'm trying to. Seems that using a DB may be the way to go though. That's a bit of a hassle since the people with the DB credentials aren't here today and I'm a bit wary of messing with anything on the DB. Just one of those things. Thank you for the answer! –  Mar 20 '19 at 16:42
0

The code above implies that members.json contains a JSON array - just like you want. It fetches that array, decodes it, creates a new complex object, assigns that object to $input and then appends it to the end of the array.

There are no keys involved, except within the object. Luckily, the object is the bit you don't need. You can replace that with a simple string value and append that to the array instead:

$data = file_get_contents('members.json');
$data_array = json_decode($data); 
$input = $_POST["newvalue"]; //replace the complex object with a single value
$data_array[] = $input;

...etc.

In my example $_POST["newvalue"] would contain a single string posted back from a text field in the browser named "newvalue".

Here's a working demo (using hard-coded values instead of filenames and POST values, but it demonstrates the principle): http://sandbox.onlinephpfunctions.com/code/68456544d8004b941f7d6603f64de6e0abf02d4e

ADyson
  • 57,178
  • 14
  • 51
  • 63
-1

To add to RiggsFolly answer, you can simply create an array of JSON objects and append to it this way:

array_push($data_array, 'newDataToAdd');
file_put_contents('members.json', $data_array);
theccode
  • 1
  • 1