Auto increment id JSON

佐手、 提交于 2019-12-01 23:33:23

It depends on your application. If you're using DB you obviously should use DB primary key value, but if you're store your info in simple .json file you must declare each row id yourself. Get the last one and increment it.

I'm strongly recommend you to store this data in DB not in file. You'll never have problems with transactions (concurrent writing to file).

Update

OK, depending on your code:

$file = file_get_contents("data.json");
$data = json_decode($file, true);

// Get last id
$last_item    = end($data);
$last_item_id = $last_item['id'];

$data[] = array(
    'id'             => ++$last_item_id,
    'title'          => $_POST["title"],
    'artist'         => $_POST["artist"],
    'genre'          => $_POST["genre"],
    'week'           => $_POST["week"],
    'highest_rating' => $_POST["highest_rating"],
    'year'           => $_POST["year"],
    'youtube'        => $_POST["youtube"],
    "links"          => [ 
        array(
            "rel"=>"self",
            "href"=>""
        ),
        array(
            "rel"=>"collection",
            "href"=>""
        )
    ]
);

file_put_contents('data.json',json_encode($data), LOCK_EX);

We're using LOCK_EX flag above to acquire an exclusive lock on the file while proceeding to the writing.

If you can't use DB I think it's more safely to read and write file with flock() function:

$filename = "data.json";
$filesize = filesize($filename);
$fp       = fopen($filename, "r+");

if (flock($fp, LOCK_EX))
{
    $data = json_decode(fread($fp, $filesize), true);

    // Get last id
    $last_item    = end($data);
    $last_item_id = $last_item['id'];

    $data[] = array(
        'id'             => ++$last_item_id,
        'title'          => 1,
        'artist'         => 2,
        'genre'          => 3,
        'week'           => 4,
        'highest_rating' => 5,
        'year'           => 6,
        'youtube'        => 7,
        "links"          => [
            array(
                "rel"  => "self",
                "href" => ""
            ),
            array(
                "rel"  => "collection",
                "href" => ""
            )
        ]
    );

    fseek($fp, 0);
    ftruncate($fp, 0);

    fwrite($fp, json_encode($data));

    flock($fp, LOCK_UN);
}
else
{
    echo "Unable to lock file";
}

fclose($fp);

While it's not clear from what you want to auto increment, When your server gets the post, it can iterate over the result and add the required ID.

After all, you can't expect the user to give you an internal id for your system for every data strcutre he passes you.

Just the same way mysql doesn't expect you to provide an id if there's an id that's auto increment.

My suggestion : Loop over the incoming json and apply your own id, from the db or what not.

I had the same problem with JSON, but in my case it's JSON in MySQL, where i store some data, with unique IDs.

The first example works, but when you need to remove any values,next time you add a value it would get duplicate IDs, so it doesn't works for me properly.

So if you need to remove/add values, and always to be sure to have unique IDs, there's simple way i found to do that.

Firstly, you get all the IDs, the array_column function is doing that just the right way

$idsList = array_column($data, 'id');

Output example: [2,3]

Then you just simply get the biggest value(ID) on the array, and add to the value +1.

$auto_increment_id = max($idsList) + 1;

So as i already said, this way you will write always an unique ID.

That is, Cheers!

Full example depending on your code:

$file = file_get_contents("data.json");
$data = json_decode($file, true);

// Get IDs list
$idsList = array_column($data, 'id');
// Get unique id
$auto_increment_id = max($idsList) + 1;

$data[] = array(
    'id'             => $auto_increment_id,
    'title'          => $_POST["title"],
    'artist'         => $_POST["artist"],
    'genre'          => $_POST["genre"],
    'week'           => $_POST["week"],
    'highest_rating' => $_POST["highest_rating"],
    'year'           => $_POST["year"],
    'youtube'        => $_POST["youtube"],
    "links"          => [ 
        array(
            "rel"=>"self",
            "href"=>""
        ),
        array(
            "rel"=>"collection",
            "href"=>""
        )
    ]
);

file_put_contents('data.json',json_encode($data), LOCK_EX);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!