如何将此数组存储到会话中并使用会话向上/向下/向左/向右对角移动数组内的元素
$board = array(A B C D E F G H
0 array(0,0,0,0,0,0,0,0),
1 array(0,0,0,0,0,0,0,0),
2 array(0,0,0,0,0,0,0,0),
3 array(0,0,0,0,0,0,0,0),
4 array(0,0,0,0,0,0,0,0),
5 array(0,0,0,0,0,0,0,0),
6 array(0,0,0,0,0,0,0,0),
7 array(0,0,0,0,0,0,0,0)
);
我正在尝试将此数组存储到会话中
$pieces = array(
//checkers pieces player 1
"b" => '<img src="bp.png" width="33" height="37" alt="black piece">',
//Checkers pieces for player2
"r" => '<img src="rp.png" width="33" height="32" alt="red piece">',
// Empty Squares
// Black
"bs" => '<img src="bs.png" width="30" height="30" alt="black square">',
// Red
"rs" => '<img src="rs.png" width="30" height="30" alt="black square">'
);
// 'es' represents empty squares
$board = array( A B C D E F G H
0 array('b','rs','b','rs','b','rs','b','rs'),
1 array('rs','b','rs','b','rs','b','rs','b'),
2 array('b','rs','b','rs','b','rs','b','rs'),
3 array('rs','bs','rs','bs','rs','bs','rs','bs'),
4 array('bs','rs','bs','rs','bs','rs','bs','rs'),
5 array('r','bs','r','bs','r','bs','r','bs'),
6 array('bs','r','bs','r','bs','r','bs','r'),
7 array('r','bs','r','bs','r','bs','r','bs')
);
function map(&$value, $key, $map) {
if(array_key_exists($value, $map)) {
$value = $map[$value];
}
}
array_walk_recursive($board, 'map', $pieces);
当它打印出来时它会出现在8x8的桌面上
我在array_walk_recursive
之后做了$_SESSION['board'] = $board;
并将其放入
echo "<table border='1'>\n";
foreach ($_SESSION['board'] as $row)
{
echo "<tr>\n";
foreach ($row as $piece){
echo "<td>";
echo "$piece ";
echo "</td>\n";
}
}
echo "</tr>\n";
echo "</table>\n";
}
用户正在输入此功能(FROM输入框)F5 - (TO输入)G2使用此功能将其解析为坐标
// parses the users input --FROM-- and to where the user wnats to move the piece
// if the user inputs F1 it parses that into (0,0) coordinates
function parseSquare() {
if (strlen($square) != 2) {
return FALSE;
}
$coords = array(ord('A') - ord($square[0]),
$square[1] - 1);
// Perform bounds-checking.
if ($coords[0] < 0 || $coords[0] > 7 || $coords[1] < 0 || $coords[1] > 7) {
return FALSE;
}
return $coords;
}
$coords = parseSquare($square);
if ($coords === FALSE) {
// Invalid input, handle this case.
} else {
$piece = $board[$coords[0]][$coords[1]]; // for example
}
我可以使用上面的功能来对角移动
$_SESSION['board'][[$new_i]-1][[$new_j] + 1] = $_SESSION['board'][$old_i][$old_j];
$_SESSION['board'][$old_i][$old_j] = ...;
答案 0 :(得分:4)
致电session_start
然后将您的变量存储在$_SESSION
中 - 它们将在整个会话期间提供:
session_start();
$_SESSION['board'] = array( ... );
移动元素只是将一个值分配给另一个,例如:
$_SESSION['board'][$new_i][$new_j] = $_SESSION['board'][$old_i][$old_j];
$_SESSION['board'][$old_i][$old_j] = ...;
答案 1 :(得分:2)
$ _ SESSION ['myArray'] = $ board;
你可以使用$ _SESSION ['myArray'] [i] [j];
访问任何元素答案 2 :(得分:1)
是。您可以在会话中存储和更新数组。 像这样使用:
session_start();
$_SESSION['youarray'] =$board;
现在根据您的要求在$ _SESSION ['youarray']数组中进行更新,就像普通数组一样。但存储在会话中。
答案 3 :(得分:1)
您将其存储在类似
的会话中<?php
session_start();
$board=array('whatever');
$session['board']=$board;
至于操作,它只是一个普通的数组。您可以像使用任何其他阵列一样使用它。