单击时从会话数组中取消设置某些项目?

Unset certain items from session array when they're clicked?

我主要寻找的是能够在单击某个项目时从数组中删除该项目,例如...如果我点击 "Two",它就会消失。

演示:http://query.notesquare.me

代码:

<form method="post">
    <input type="text" id="input-create-playlist" placeholder="Playlist Name" name="create_playlist" />
    <input type="submit" id="button-create-playlist" value="Create Playlist" />
</form>

<?php
    ini_set("session.save_path", "/home/kucerajacob/public_html/query.notesquare.me/test-sessions");
    session_start();

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $create_playlist = $_POST['create_playlist'];

        $_SESSION['user_playlists'][] = $create_playlist;
    }

    $playlists = array("One", "Two", "Three");

    if (isset($_SESSION['user_playlists'])) {
        for ($i = 0; $i < count($_SESSION['user_playlists']); $i++) {
            array_unshift($playlists, $_SESSION['user_playlists'][$i]);
        }
    }

    $_SESSION['main'] = $playlists;

    for ($i = 0; $i < count($playlists); $i++) {
        echo $playlists[$i] . "<br />";
    }
?>

有可能,您还需要处理该请求。如果你想发布 click,旁边一个简单的 <button> 就足够了。

呈现标记后,(当然使用会话数组)使用可用于取消设置值的键。

<?php

// initialization
if(empty($_SESSION['user_playlists'])) {
    $_SESSION['user_playlists'] = array("One", "Two", "Three");
}

if(isset($_POST['add'], $_POST['create_playlist'])) {
    // handle additions
    $_SESSION['user_playlists'][] = $_POST['create_playlist'];
}

if(isset($_POST['remove'])) {
    // handle remove
    $key = $_POST['remove'];
    unset($_SESSION['user_playlists'][$key]);
}

?>

<form method="post">
    <input type="text" id="input-create-playlist" placeholder="Playlist Name" name="create_playlist" />
    <input type="submit" id="button-create-playlist" name="add" value="Create Playlist" />
    <hr/>
    <?php foreach($_SESSION['user_playlists'] as $k => $p): ?>
        <?php echo $p; ?>&nbsp;<button type="submit" name="remove" value="<?php echo $k; ?>">Remove</button><br/>
    <?php endforeach; ?>
</form>

Sample Demo

尝试以下:

for ($i = 0; $i < count($playlists); $i++) {
       // echo $playlists[$i] . "<br />";
  printf('<a href="php_pagename.php?query=%1$s">%1$s</a><br/>', $playlists[$i]);
}

if ($_GET['query'])
{
unset($playlists['query']);
}