开发者

How to retrieve a nested value from the $_REQUEST dict when I have the key as a string?

Easiest to explain with an example. I've got an HTML form with an input like this:

<input name="a[b]" />

Now I want to retrieve the value for that input from the $_REQUEST dict. I have $name = 'a[b]'. I'm not sure how to use the string $name to pull the value out of $_REQUEST because request stores it in $_REQUEST['a']['b'] not $_REQUEST['a[b]'], so $_REQUEST[$name] won't work.


Going with a modified (presumably more efficient) version of inti's solution:

function array_value(&$array, $key) {
    $keys = explode('[', str_replace(']', '', $key));
    $first = array_shift($keys);
    $value = $array[$first];
    foreach($keys as $k)
        $val开发者_JS百科ue = $value[$k];
    return $value;
}


Use function like this to parse the $name variable:

function getValByName(&$req,$name)
{
    foreach(explode("[",$name) as $v)
    {
        $k = str_replace("]","",$v);
        $val = isset($val) ? $val[$k] : $req[$k];
    }
    return $val;
}

Usage:

$v = getValByName($_REQUEST,"a[b]");
$v = getValByName($_REQUEST,"a[b][c][d][e]"); // if you need more


Unless the $name is always nested only once, the only semi-elegant solution would be to split the $name and make a loop extracting each array one after another... I see that inti has already posted such solution.

But if you like doing things ineffective and brittle way, you can always take the raw query string and process it with some Skinner's Constants:

$query = $_SERVER['QUERY_STRING'] . '&';
$name = 'a[b][c][d]';

$from = strpos($query . '=', $name) + strlen($name) + 1;
$to = strpos($query, '&', $from);
$result = urldecode(
    substr($query, $from, $to - $from)
);


If you are posting data from form:

<form method="post">
  /input elements/
</form>

you recieve data in $_POST superlobal.

You can check its values using:

var_dump($_POST);

If you use

<input type="text" name="a[b]" />

you can access its value by

$_POST['a']['b']


Or you can access it by

$array = $_POST['a'];
$name_value = $array['b'];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜