单击时从会话数组中取消设置某些项目?
Posted
技术标签:
【中文标题】单击时从会话数组中取消设置某些项目?【英文标题】:Unset certain items from session array when they're clicked? 【发布时间】:2015-07-08 04:24:05 【问题描述】:我基本上在寻找的是能够在单击某个项目时从数组中删除该项目,例如...如果我点击“两个”,它将消失。
演示: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 />";
?>
【问题讨论】:
【参考方案1】:试试下面:
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']);
【讨论】:
【参考方案2】:有可能,您还需要处理该请求。如果您想要发布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; ?> <button type="submit" name="remove" value="<?php echo $k; ?>">Remove</button><br/>
<?php endforeach; ?>
</form>
Sample Demo
【讨论】:
谢谢你!您也解决了我遇到的一些隐藏的内在问题!以上是关于单击时从会话数组中取消设置某些项目?的主要内容,如果未能解决你的问题,请参考以下文章