我创建了一个会话数组,将在每个用户的网站中使用。用户更改设置后,会话数组的设置将随之更改。
我在加载页面时创建一个会话数组:
if (!isset($_SESSION['controller']))
{
$_SESSION['controller'] = array(
'color' => array(
'shell' => 'none',
'graphic-color' => 'none',
'part-color' => 'none'
),
'graphics' => array (
'text' => 'none',
'text-font' => 'none',
'text-style' => 'none',
'graphic' => 'none',
'part' => 'none'
)
);
}
一旦用户使用ajax调用更改设置,我会调用.php文件来修改哪个相关设置被假设要更改:
JS:
function changeSetting(what, to)
{
$.ajax({
url: "../wp-content/themes/twentytwelve/controller/php/controllerArrayMody.php",
type: "POST",
data: {
'what' : what,
'to' :to
},
success: function() {
}
});
}
what
将包含“shell”或“图形颜色”等... to
将包含它所假设的值,因此none
将发生变化。
现在从他们这里得到我修改它的代码:
$changeWhat = $_POST['what'];
$to = $_POST['to'];
$newArray = $_SESSION['controller'];
$key = array_search($changeWhat , $_SESSION['controller']); // returns the first key whose value is changeWhat
$newArray[$key][0] = $to; // replace
$_SESSION['controller'] = $newArray;
这是输出:
Array ( [color] => Array ( [shell] => none [graphic-color] => none [part-color]
=> none ) [graphics] => Array ( [text] => none [text-font] => none [graphic] =>
none [part] => none ) [0] => Array ( [0] => Red-Metallic.png ) )
我的问题是,我错误地说它是添加到数组的末尾而不是替换,让我们说[shell]为值to
,这就是说Img.test.png
答案 0 :(得分:1)
以下是解决方案:
$changeWhat = $_POST['what']; // suppose it's 'graphics-color'
$to = $_POST['to'];
$newArray = $_SESSION['controller'];
$changeWhatKey = false; // assume we don't have changeWhat in $newArray
// next, iterate through all keys of $newArray
foreach ($newArray as $group_name => $group_options) {
$changeWhatKeyExists = array_key_exists($changeWhat, $group_options);
// if we have key $changeWhat in $group_options - then $changeWhatKeyExists is true
// else it equals false
// If we found the key - then we found the group it belongs to, it's $group_name
if ($changeWhatKeyExists) {
$changeWhatKey = $group_name;
// no need to search any longer - break
break;
}
}
if ($changeWhatKey !== false)
$newArray[$changeWhatKey][$changeWhat] = $to; // replace
$_SESSION['controller'] = $newArray;
答案 1 :(得分:0)
只要您的$to
是数组,我就会这样做:
$changeWhat = $_POST['what'];
$to = $_POST['to'];
$_SESSION['controller'][$changeWhat] = $to;
这未经测试,但我希望它有所帮助! :)
答案 2 :(得分:0)
在这种情况下,您可以使用array_walk_recursive功能
<?php
$what = $_POST["what"];
$to = $_POST["to"];
function my_callback( &$value, $key, $userdata ) {
if ( $key === $userdata[0] ) {
$value = $userdata[1];
}
}
array_walk_recursive( $_SESSION["controller"], "my_callback", array( $what, $to ) );
print_r( $_SESSION["controller"] );
?>