dongmanni6916 2014-01-27 12:57
浏览 230
已采纳

如何将数组键转换为$ _POST [name]

If a have a form input with a name like "name[0][firstname]", $_POST will retrieve that as:

 'name' => 
    array (size=1)
      0 => 
        array (size=9)
          'firstname' => null

so echo $_POST['name'][0]['firstname'] will give me null.

The question is how can I build the post query dynamically from the array keys? so, for example:

$foo = array('name', 0, 'firstname'); 
echo $_POST[$foo];  // obviously doesn't work 

What I need do is build this statement, $_POST['name'][0]['firstname'], from the array but can't find a way to do it. I thought maybe $_POST{'[' . implode('][',$foo) . ']'} might work but I get Undefined index: ['name'][0]['firstname'].

Final solution **

With regards to the solution by @Alireza and @Matteo, both work, except in the case if the array is longer than the $_POST array, eg, if array is $foo = array('name', 0, 'firstname', 'lastname') and the post value is array['name'][0]['firstname'] = "XXX" the result will be "X" which is index 0 of the result XXX. Therefore it needs to check the keys of the post and not the value.

The final solution for me is therefore:

function getValue($res, $foo)
{
    foreach ($foo as $val) {
        if (is_array($res) && array_key_exists($val, $res)) {
            $res = $res[$val];
        } else {
            return false;
        }
    }
    return $res;
}

Examples:

$post = array(
  'name' => array(
    0 => array(
      'firstname' => 'XXX'
    ),
  )
);

echo getValue($post, array('name', 0, 'firstname'));
> XXX    
echo getValue($post, array('name', 0, 'firstname', 'lastname'));
> false
echo getValue($post, array('name', 0, 'firstname', 0));
> false
echo getValue($post, array('name', 0, 0));
> false  
echo getValue($post, array('name', 0));
> Array (eg, Array ( [firstname] => XXX )) - expected 

Thanks for the help.

  • 写回答

4条回答 默认 最新

  • dongye1912 2014-01-27 13:30
    关注

    I think this is very easier :

    $foo = array('name', 0, 'firstname')
    $res = $_POST;
    foreach ($foo as $val) {
        $res = $res[$val];
    }
    echo $res;
    

    Example :

    $array[0]['f']['p'][8]['Hi'] = 'Hello World!';
    $foo = array(0,'f','p',8,'Hi');
    $res = $array;
    foreach ($foo as $val) {
        $res = $res[$val];
    }
    echo $res;
    

    Echoes 'Hello World!'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置