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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题