1

我创建了一个会话数组,将在整个站点中为每个用户使用。一旦用户更改设置,会话数组的设置也会随之更改。

我在加载页面时创建了一个会话数组:

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' 或 'graphic-color' 等......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

4

3 回答 3

1

Here's the solution:

$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;
于 2013-07-06T19:26:16.810 回答
0

只要你$to是一个数组,我会简单地做:

$changeWhat = $_POST['what'];
$to = $_POST['to'];
$_SESSION['controller'][$changeWhat] = $to;

这未经测试,但我希望它有帮助!:)

于 2013-07-06T18:59:28.517 回答
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"] );
?>
于 2013-07-06T19:17:57.810 回答