0

Consider the following:

<input type="hidden" name="random[variable][here]" value="valueofrandom"/>

Is there a better way to retrieve its value if we have the name as a string? The following works, but it doesn't seem very smart.

function getPostValueFromName($name) {
    // Example string name: random[variable][here]
    $parts = preg_split('/\[|\]/i', $name, -1, PREG_SPLIT_NO_EMPTY);

    if (isset($parts[3])) {
        return $_POST[$parts[0]][$parts[1]][$parts[2][$parts[3]]];
    } elseif (isset($parts[2])) {
        return $_POST[$parts[0]][$parts[1]][$parts[2]];
    } elseif (isset($parts[1])) {
        return $_POST[$parts[0]][$parts[1]];
    } else {
        return $_POST[$parts[0]];
    }
}

Thanks!

4

1 回答 1

0

我使用https://github.com/symfony/PropertyAccess来处理这样的事情。

使用它,你可以random[variable][here]得到

$accessor = new PropertyAccessor();

$val = $accessor->getValue($_POST, 'random.variable.here');
// or
$val = $accessor->getValue($_POST, 'random[variable][here]');
于 2013-02-07T21:18:39.413 回答