Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active August 29, 2015 14:25
Show Gist options
  • Save masakielastic/591f0a1eeb12a7f2f52d to your computer and use it in GitHub Desktop.
Save masakielastic/591f0a1eeb12a7f2f52d to your computer and use it in GitHub Desktop.
在庫管理の API を PHP で練習。ストレージに JSON のテキストファイル。
http localhost/test/api_stock_list.php
http -f POST localhost/test/api_stock.php id=1 amount=5
http localhost/test/api_stock_reset.php
<?php
require 'functions.php';
header('Content-Type: application/json');
$id = empty($_POST['id']) ? null : (int) $_POST['id'];
$amount = empty($_POST['amount']) ? null : (int) $_POST['amount'];
if (!is_int($id) || 0 > $id) {
echo json_encode([
'msg' => 'id が正の整数ではありません。',
'id' => $id
]);
exit();
}
if (!is_int($amount) || 0 >= $amount) {
echo json_encode([
'msg' => 'amount が空もしくは0以上の整数ではありません。',
'amount' => $amount
]);
exit();
}
$stock = stock_read();
$check = false;
foreach ($stock as $key => &$value) {
if ($id === $value['id']) {
$value['amount'] = $amount;
$check = true;
break;
}
}
if (!$check) {
echo json_encode(['msg' => '該当する id が存在しませんでした。']);
exit();
}
stock_save($stock);
echo json_encode(['msg' => 'ok']);
<?php
require 'functions.php';
header('Content-Type: application/json');
echo stock_read_json();
require 'functions.php';
header('Content-Type: application/json');
$stock = [
['id' => 1, 'name' => '唐揚げ弁当', 'price' => 500, 'amount' => 3],
['id' => 2, 'name' => '日替わり弁当', 'price' => 600,'amount' => 5],
['id' => 3, 'name' => '幕の内弁当', 'price' => 700, 'amount' => 2],
];
stock_save($stock);
echo json_encode(['msg' => 'ok']);
<?php
function stock_read()
{
return json_decode(file_get_contents('stock.json'), true);
}
function stock_read_json()
{
return file_get_contents('stock.json');
}
function stock_save($array)
{
file_put_contents('stock.json', json_encode($array));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment