迷路の自動生成

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 = &#91;
    '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 = &#91;
    '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 = &#91;
    '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 = &#91;
    '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&#91;"turn"&#93;) ? 0 : interval($_GET&#91;"turn"&#93;);

    if($turn == 0|| empty($_SESSION&#91;"numbers"&#93;)){
        $numbers = array();
        for ($i = 1; $i <= 75; $i++){
            $numbers&#91;$i&#93; = $i;
        }
        shuffle($numbers);
        // save session
        $_SESSION&#91;"numbers"&#93; = $numbers;
    }

    $numbers = $_SESSION&#91;"numbers"&#93;;
    $num = $numbers&#91;$turn&#93;;
    $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 = &#91;&#93;;
    $mti = $MT_N + 1;

    // initialize
    function my_mt_srand($seed){
        global $mt, $mti, $MT_N;
        $mt&#91;0&#93; = $seed & 0xfffffff;
        for ($mti = 1; $mti < $MT_N; $mti++){
            $mt&#91;$mti&#93; = (1812433253 * ($mt&#91;$mti-1&#93; ^ ($mt&#91;$mti-1&#93; >> 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&#91;$kk&#93;&$MT_UPPER_MASK)|($mt&#91;$kk+1&#93;&$MT_LOWER_MASK);
                $mt&#91;$kk&#93; = $mt&#91;$kk+($MT_M-$MT_N)&#93; ^ ($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&#91;my_mt_rand(0, 5)&#93;;
        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&#91;lc_rand() % 6&#93;;
        echo $c;
        if ($i % 16 == 15) echo "<br>";
    }