我如何从此$ _POST结果中获得关联数组

时间:2019-02-02 09:54:02

标签: php arrays post

有人可以帮助我从此示例中获取数组吗?

   <div>      
    <input type="checkbox" name="extracheckbox[][link]" value="site.com/1">
    <input type="checkbox" name="extracheckbox[][img]" value="site.com/a1.img">
    </div>

    <div>
    <input type="checkbox" name="extracheckbox[][link]" value="site.com/2">
    <input type="checkbox" name="extracheckbox[][img]" value="site.com/a2.img">
    </div>

我想从这篇帖子结果中获取关联数组

$post_results=array("link"=>site.com/1,"img"=>site.com/a1.img),
array("link"=>site.com/2,"img"=>site.com/a2.img)

2 个答案:

答案 0 :(得分:1)

最简单的方法:

<form action="#" method="post">
<div>
    <input type="checkbox" name="extracheckbox[link]" value="site.com/1"><br />
    <input type="checkbox" name="extracheckbox[img]" value="site.com/a1.img"><br />
</div>

<div>
    <input type="checkbox" name="extracheckbox2[link]" value="site.com/2"><br />
    <input type="checkbox" name="extracheckbox2[img]" value="site.com/a2.img"><br />
</div>

    <input type="submit">
</form>

结果是:

Array
(
    [extracheckbox] => Array
        (
            [link] => site.com/1
            [img] => site.com/a1.img
        )

    [extracheckbox2] => Array
        (
            [link] => site.com/2
            [img] => site.com/a2.img
        )

)

答案 1 :(得分:0)

此答案解决了我的问题,因为我有30多个组合输入值并将其添加到关联数组

 $array = $_POST['extracheckbox'];
    $newArray = array();
    foreach (array_keys($array) as $fieldKey) {
        foreach ($array[$fieldKey] as $key=>$value) {
            $newArray[$key][$fieldKey] = $value;
        }
    } 
var_dump($newArray);

结果:

array[40]{
array('link'=>'site.com/1','img'=>site.com/a1.img),
array('link'=>'site.com/2','img'=>site.com/a2.img),
array('link'=>'site.com/3','img'=>site.com/a3.img),
array('link'=>'site.com/4','img'=>site.com/a4.img),
...};