How to get value of an associative HTML array in PHP using a string?

前端 未结 3 1616
礼貌的吻别
礼貌的吻别 2021-01-29 08:19

Look I have a form like this:

I want t

相关标签:
3条回答
  • 2021-01-29 08:42

    You're WAY overthinking it. Anything you put in [] array notation in a form field's name will just become an array key. The following is LITERALLY all you need:

    <input name="foo[bar][baz][qux]" ... />
    
    $val = $_POST['foo']['bar']['baz']['qux'];
    

    You cannot use a string as an "address" into the array, not without insanely ugly hacks like eval, or parsing the string and doing a loop to dig into the array.

    0 讨论(0)
  • 2021-01-29 08:59

    You can use preg_match_all() to get all the indexes in the string into an array:

    $indexes = preg_match_all('/(?<=\[\')(?:[^\']*)(?=\'\])/', $str);
    $indexes = $indexes[0]; // Get just the whole matches
    

    Then use a loop to drill into $_POST.

    $cur = $_POST;
    foreach ($indexes as $index) {
        $cur = $cur[$index];
    }
    

    At this point $cur will contain the value you want.

    0 讨论(0)
  • 2021-01-29 09:00

    It's hard to believe that this is a requirement. If you could expand more on what you're trying to achieve, someone undoubtedly has a better solution. However, I will ignore the eval = evil haters.

    To echo:

    eval("echo \$_POST$str;");
    

    To assign to a variable:

    eval("\$result = \$_POST$str;");
    

    If you're open to another syntax then check How to write getter/setter to access multi-level array by key names?

    0 讨论(0)
提交回复
热议问题