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"; }
Mersenne Twister
<?php $MT_N = 624; $MT_M = 397; $MT_UPPER_MASK = 0x80000000; $MT_LOWER_MASK = 0x7fffffff; $mt = []; $mti = $MT_N + 1; // initialize function my_mt_srand($seed){ global $mt, $mti, $MT_N; $mt[0] = $seed & 0xfffffff; for ($mti = 1; $mti < $MT_N; $mti++){ $mt[$mti] = (1812433253 * ($mt[$mti-1] ^ ($mt[$mti-1] >> 30)) + $mti); $mt[$mti] &= 0xfffffff; } } function my_mt_rand($min, $max){ $range = $max - $min + 1; return (my_mt_genrand_int32() % $range) + $min; } function my_mt_genrand_int32() { global $MT_N, $MT_M, $mt, $mti; global $MT_UPPER_MASK, $MT_LOWER_MASK; static $mag01; $mag01 = array(0x0, 0x9908b0df); // table initialize if ($mti == $MT_N){ if ($mti == $MT_N + 1) my_mt_srand(time()); // remake table for ($kk = 0; $kk < $MT_N - $MT_M; $kk++){ $y = ($mt[$kk]&$MT_UPPER_MASK)|($mt[$kk+1]&$MT_LOWER_MASK); $mt[$kk] = $mt[$kk+($MT_M-$MT_N)] ^ ($y >> 1) ^ $mag01[$y & 0x1]; } $y = ($mt[$MT_N-1]&$MT_UPPER_MASK)|($mt[0]&$MT_LOWER_MASK); $mt[$MT_N-1] = $mt[$MT_M-1] ^ ($y >> 1) ^ $mag01[$y & 0x1]; $mti = 0; } $y = $mt[$mti++]; $y ^= ($y >> 11); $y ^= ($y << 7) & 0x9d2c5680; $y ^= ($y << 15) & 0xefc60000; $y ^= ($y >> 18); return $y; } my_mt_srand(time()); $list = array('●','▲','■','◯','△','□') for ($i = 0; $i < 256; $i++){ $c = $list[my_mt_rand(0, 5)]; echo $c; if($i % 16 == 15) echo "<br>"; }
linear congruential generators
<?php // rand initial number(seed) $lc_seed = 1; // random function fuction lc_rand() { global $lc_seed; $MASK = 0xffffffff; $lc_seed = (1103515245 * $lc_seed + 12345) & $MASK; return ($lc_seed / 65536) % 32768; } // initialize random function function lc_srand($seed) { global $lc_seed; $lc_seed = $seed; } // example lc_srand(time()); $list = array('●','▲','■','◯','△','□'); for ($i = 0; $i < 256; $i++){ $c = $list[lc_rand() % 6]; echo $c; if ($i % 16 == 15) echo "<br>"; }