シーザー暗号
<meta charset="UTF-8">
<?php
// get parameter
$str = isset($_GET["str"]) : "";
$shift = isset($_GET["shift"]) ? intval($_GET["shift"]) : 3;
if ($str != "")convert($str, $shift);
$str_ = htmlentities($str, ENT_QUOTES);
// display form
echo <<< EOS
<form>
character line: <input name="str" value="$str_"><br>
shift: <input name="shift" value="$shift"><br>
<input type=="submit" value="change">
</form>
EOS;
function makeTable($shift){
$ch1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$shift = $shift % strlen($ch1);
$ch2 = substr($ch1, $shift).substr($ch1, 0, $shift);
$table = [];
for ($i = 0; $i < strlen($ch1); $i++){
$c1 = substr($ch1, $i, 1);
$c2 = substr($ch2, $i, 1);
$table[$c2] = $c1;
}
return $table;
}
function convert($str, $shift){
if (empty($_GET["str"])) return;
$table = makeTable($shift);
$res = "";
for ($i = 0; $i < strlen($str); $i++){
$c = substr($str, $i, 1);
$res .= isset($table[$c]) ? $table[$c] : $c;
}
$str = htmlentities($str, ENT_QUOTES);
$res = htmlentities($res, ENT_QUOTES);
echo "<div>before transfer: $str</div>";
echo "<div>after transfer: $res</div><hr>";
}
迷路の自動生成
0,";
$pat[1] = "1,";
$html = "";
for ($y = 0; $y < count($maze); $y++){ for ($x = 0; $x < count($maze); $x++){ $html .= $pat[$maze[$y][$x]]; } $html .= "\n"; } return $html; }[/php]
YAML
<?php
// read YAML library
require 'vendor/autoload.php';
use Symfony\Component\Yaml;
// declare data
$data = [
'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
];
$file = "serialize-test.yaml";
$dumper = new Yalm\Dumper();
$yaml = $dumper->dump($data);
file_put_contents($file, $yaml);
$yaml2 = file_get_contents($file);
$yaml_p = new Yaml\Parser();
$data2 = $yaml_p->parse($yam12);
foreach ($data2 as $name => $v) {
$age = $v["age"];
$hobby = $v["hobby"][0];
if (isset($v["hobby"][1])){
$hobby .= " ".$v["hobby"][1];
}
echo "[$name] $age $hobby\n";
}
simpleXMLElement
<?php
// declare data
$data = [
'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
];
// saving file pass
$file = "serialize-test.xml";
// transfer function from php array to XML
function array2xml($arr, $xml_obj = NULL) {
if ($xml_obj == NULL){
$def = '<?xml version="1.0"?><root></root>';
$xml_obj = new SimpleXMLElement($def);
}
foreach($arr as $key => $value){
if (is_numeric($key)) $key = "item";
if (is_array($value)){
$subnode = $xml_obj->addChile($key);
array2xml($value, $subnode);
} else {
$v = htmlentities($value);
$xml_obj->addChild($key, $v);
}
}
return $xml_obj;
}
// transfer array to object
$xml_obj = array2xml($data);
$str = $xml_obj->asXML();
// save to file
file_put_contents($file, $str);
// read from file
$xml2 = simplexml_load_file($file);
foreach ($xml2->children() as $it){
$name = $it->getName();
$age = $it->age;
echo "$name:$age:";
$hobby = $it->hobby;
foreach ($hobby->children() as $h){
echo "($h)";
}
echo "\n";
}
simple XML
phpでxmlを扱うにも、いろいろな方法があります。文字列のxmlを読み込んで解析し、xmlの内容を出力します。
<?php
// set XML
$xml_str = <<<XML
<?xml version='1.0'?>
<items>
<item id="101">
<name>石鹸</name>
<price>510</price>
</item>
<item id="102">
<name>ブラシ</name>
<price>330</price>
</item>
</items>
XML;
// analyze XML
$xml = simplexml_load_string($xml_str);
// display each item info
foreach ($xml->item as $it){
$attr = $it->attributes();
echo "(id:".$attr["id"].")";
echo $it->name." - ".$it->price." 円\n";
}
json_encode()
jsonを使って書き直し
<?php
//declare data
$data = [
'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
];
// file pass to preserve
$file = "serialize-test.json";
//serialize
$str = json_encode($data, JSON_PRENTY_PRINT);
//preserve
file_put_contents($file, $str);
//recover data from a file
$str2 = file_get_contents($file);
$data2 = json_decode($str2, true);
// display Arisa hobby
print_r($data2['Arisa']['hobby']);
serialize()
phpの配列はメモリ上に配置されており、これをストレージに保存したり、ブラウザなどクライアント先に一定の書式で出力するためには、何らかのシリアライズ(serialize)という処理をする必要が有ります。
<?php
// declare data
$data = [
'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
];
$file = "serialize-test.txt";
$str = serialize($data);
file_put_contents($file, $str);
$str = serialize($data);
file_put_contents($file, $str);
$str2 = file_get_contents($file);
$data2 = unserialize($str2);
// display Arisa hobby
print_r($data2['Arisa']['hobby']);
ビンゴマシン
<html><body><?php
// bingo machine
session_start();
// get from turn
$turn = empty($_GET["turn"]) ? 0 : interval($_GET["turn"]);
if($turn == 0|| empty($_SESSION["numbers"])){
$numbers = array();
for ($i = 1; $i <= 75; $i++){
$numbers[$i] = $i;
}
shuffle($numbers);
// save session
$_SESSION["numbers"] = $numbers;
}
$numbers = $_SESSION["numbers"];
$num = $numbers[$turn];
$now_turn = $turn + 1;
$next = ($turn + 1) % 75;
echo "<p>{$now_turn}ターン目</p>";
echo"<h1>$num</h1>";
echo "<p><a href='bingo.php?turn=$next'>next number</a></p>";
?></body></html>
配列のデータをシャッフル
カードゲームやビンゴマシンを作る際には、配列のデータをシャッフルするアルゴリズムが重要
$sample_ary = array(1,2,3,4,5);
shuffle($sample_ary);
// display result
foreach ($sample_ary as $v){
echo $v."\n";
}
フィッシャー・イェーツのシャッフル
<pre><?php
// mt_rand() array shuffle function
function mt_shuffle(&$a){
$a = array_values($a);
for ($i = count($a) - 1; $i >= 1; $i--){
$r = mt_rand(0, $i);
list($a[$i], $a[$r]) = array($a[$r], $a[$i]);
}
}
// mt_shuffle() use example
$sample_ary = array(1,2,3,4,5);
mt_shuffle($sample_ary);
foreach($sample_ary as $v){
echo $v."\n";
}