简体   繁体   中英

PHP: Updating an associative array though a class function?

I want to be able to update an associative array within an object based on function input, but I'm at a loss for how to do this. Here's my problem. Let's say there's this data container in my object:

private $vars = Array
(
  ['user_info'] = Array
  (
    ['name'] => 'John Doe'
    ['id'] => 46338945
    ['email'] => 'johndoe@example.com'
    ['age'] => 35
  )
  ['session_info'] = Array
  (
    ['name'] => 'session_name'
    ['id'] => 'mGh44Jf0nfNNFmm'
  )
)

and I have a public function update to change these values:

public function update($keys, $changeValueTo) {
  if (!is_array($keys)) {
    $keys = array($keys);
  }
  nowWhat();
}

Ultimately, I just want to be able to convert something like this

array('user_info', 'name')

into this:

$this->vars['user_info']['name']

so I can set it equal to the $equalTo parameter.

This usually wouldn't be a problem, but in this scenario, I don't know the schema of the $vars array so I can't write a foreach statement based on a fixed number of keys. I also can't just make $vars public, because the function needs to do something within the object every time something is changed.

I'm worried that this is a recursive scenario that will involve resorting to eval() . What would you recommend?

It is not hard to do it. You need passing variable by reference and a loop to achieve. No need eval() .

$var = array(
    "user_info" => array(
        "name" => "Visal"
    )
);

function update(&$var, $key, $value) {
    // assuming the $key is an array
    $t = &$var;
    foreach ($key as $v) {
        $t = &$t[$v];
    }

    $t = $value;
}

update($var, array("user_info", "name"), "Hello World");
var_dump($var);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM