Auto increment id JSON

前端 未结 3 1550
忘掉有多难
忘掉有多难 2021-01-22 10:59

I\'m making a RESTful webservice and I want the items that are posted to the JSON file to have an Id. I\'ve been searching everywhere but couldn\'t find anything on how to do th

3条回答
  •  天涯浪人
    2021-01-22 11:50

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

提交回复
热议问题