[PHP]HTMLフォームで検索条件を解除するリンクを作る

Pocket

form

条件検索で絞りこみすぎた場合のために、条件を取り消すボタンを用意するケースはよくあります。
GET方式のフォームであればそのパラメータを除いたリンクを作るだけなのですが、配列からキー名を文字列で指定して取り除く処理が思ったよりややこしかったため下記ページを参考にさせていただきました。

参考:『ドットチェイン表現で配列要素をget/set/unset – Qiita』
http://qiita.com/mpyw/items/185c00306b7d7d6a06d0

<?php
$requests = [];
if(isset($_GET['q']) && $_GET['q'] !== ''){
    $requests['q'] = filter_input(INPUT_GET, 'q');
}

if(isset($_GET['options'])){
    $requests['options'] = filter_input(INPUT_GET, 'options',
     FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
}

function array_unset($array, $path, $separator = '.') {
    $keys = explode($separator, $path);
    $current = &$array;
    $parent = &$array;
    foreach ($keys as $i => $key) {
        if (!array_key_exists($key, $current)) return;
        if ($i) $parent = &$current;
        $current = &$current[$key];
    }
    unset($parent[$key]);
    return $array;
}

?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form action="" method="GET">
            <div>Keyword: <input type="text" name="q" value=""></div>
            <p>
                <label><input type="checkbox" name="options[]" value="1">1</label>
                <label><input type="checkbox" name="options[]" value="2">2</label>
                <label><input type="checkbox" name="options[]" value="3">3</label>
            </p>
            <p><input type="submit" value="Search"></p>
        </form>

        <ul>
        <?php foreach($requests as $key => $value): ?>
            <?php if(is_array($value)): ?>
                <?php foreach($value as $key2 => $value2): ?>
                <li>
                    <?php printf('%s[%s]=%s', $key, $key2, $value2);?>
                    <a href="?<?php echo http_build_query(array_unset($requests, $key . '.' . $key2));?>">[remove]</a>
                </li>
                <?php endforeach;?>
            <?php else: ?>
            <li>
                <?php echo $key .  '=' . $value;?>
                <a href="?<?php echo http_build_query(array_unset($requests, $key));?>">[remove]</a>
            </li>
            <?php endif; ?>
        <?php endforeach; ?>
        </ul>
    </body>
</html>


Similar Posts:




コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です