doupu2722 2016-03-27 19:11
浏览 24

从多维$ _GET数组中获取已知键

I want to create a function (or method) that can fetch any key from $_GET array (or a $_POST or $_COOKIE array). The $_GET array can be flat, non-existing or multi-dimensional. The keys are associative and they may not always exist - as when an empty form is submitted -> no $_GET parameter is set in the url.

Here is a sample url for the scenario that I want to support: http://www.example.com/foo?foo[name]=John&foo[color][]=red&foo[color][]=green&foo[color][]=yellow&foo[gender]=male.

The contents of this url shall be captured by the same get() function:

get($foo[name])  // Return value set in input field.
get($foo[color]) // Return array with none/one/many values (set in checkbox or multi-select, see sample code below).

// The functions shall be similar to:
$_GET['foo']['name'] // string
$_GET['foo']['color'] // array

The main use case in which I will be using the function is when a form is submitted, such as the one below. When the form is submitted, I want to fetch data from the checkboxes and radio buttons weather they are set or not.

<form method="GET">
<input type="text" name="foo[name]" value="">
<input type="radio" name="foo[gender]" value="male">
<input type="radio" name="foo[gender]" value="female">
</form>

Sample output for the form comes here.

Example 1: Form is posted with all fields set:

Array (
    [foo] => Array (
            [name] => John
            [color] => Array (
                    [0] => red
                    [1] => green
                    [2] => yellow
                )
            [gender] => male
        )
)

Example 2: Form is submitted as empty (so no keys exists, it is important that the function supports this scenario):

Array ()

Things I tried:

The first two scenarios with a flat or non-existing array are easy to manage, as shown in below function that will handle both flat and non-existing array keys. However, the function does not support multi-dimensional arrays (say, with up to two dimension levels).

// This will only work for a form that returns a flat $_GET array (e.g., http://www.example.com/foo?a=1&c=3). 
// `get('foo[color]')` will not do the trick.
function get($key) {
    if (isset($_GET[$key])) {
        return $_GET[$key];
    }
}

My question is how I can build a similar function that also supports a scenario with multi-dimensional arrays? How can I create the function so it will be valid for a multi-dimensional array?

Thanks.. :-)

PS: If your answer involves something like RecursiveArrayIterator(), I would appreciate a full example as this can be challenging to work with.

PPS: To reviewers who are quick on the dupe button: I am aware that StackOverflow has a ton of question regarding $_GET and arrays, and therefore encourage my reviewers to read and re-read the question before marking it as a duplicate. Again, the scenario here is how to create a function that supports getting a known key from a $_GET array, the $_GET array is multi-dimensional and it may or may not be set.

  • 写回答

1条回答 默认 最新

  • duanaoshu1989 2016-03-27 19:50
    关注

    I have a feeling there's a cleverer way; and maybe I misunderstand the question.

    <?php
    $_GET = ['foo'=>[ // just for this example, don't fiddle with _GET like this in production code....
        'name'=>'John',
        'colors'=>[
            'primary'=>['red','green','yellow'],
            'secondary'=>['white','purple']
        ],
        'gender'=>'male'
    ]];
    
    
    
    echo '1 ', get('foo', 'name'), "
    ";
    echo '2 ', var_export( get('foo', 'color'), true ), "
    ";
    echo '3 ', var_export( get('foo', 'colors'), true ), "
    ";
    echo '4 ', get('foo', 'colors', 'primary', 0), "
    ";
    echo '5 ', get('foo', 'colors', 'secondary', 1), "
    ";
    echo '6 ', get('foo', 'gender'), "
    ";
    
    
    // see http://docs.php.net//functions.arguments#functions.variable-arg-list
    function get(...$keys) {
        $cur = $_GET;
        foreach( $keys as $k ) {
            if ( !isset($cur[$k]) ) {
                return FALSE;
            }
            else {
                $cur = $cur[$k];
            }
        }
        return $cur;
    }
    

    prints

    1 John
    2 false
    3 array (
      'primary' => 
      array (
        0 => 'red',
        1 => 'green',
        2 => 'yellow',
      ),
      'secondary' => 
      array (
        0 => 'white',
        1 => 'purple',
      ),
    )
    4 red
    5 purple
    6 male
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答