保存多维数组的索引

时间:2018-06-07 04:47:28

标签: php multidimensional-array foreach

以下是动态创建的多维数组。

<input type="checkbox" name="menu[2][1]">
<input type="checkbox" name="menu[2][2]"> 

 ...........................................

<input type="checkbox" name="menu[2][x]">

如何将第一个索引和第二个索引存储为单独的变量?例如

foreach($_POST['menu'] as $arr){
//$a = $arr['first index'];
//$b = $arr['second index']
}

2 个答案:

答案 0 :(得分:1)

$a = $_POST['menu'][2][1];

$b = $_POST['menu'][2][2];

-Edit:这就是你想要的:

foreach($_POST['menu'][2] as $k => $v){
 $a = $v;
  if(isset( $_POST['menu'][2][$k+1]))
   $b = $_POST['menu'][2][$k+1];
}

答案 1 :(得分:0)

试试这段代码

<?php
    if(isset($_POST['submit'])){
        echo "<pre>";
        print_r($_POST['menu']);
        foreach ($_POST['menu'] as $key => $value) {
            $index1[] = $key;
            foreach ($value as $key1 => $value1) {
                $index2[]=$key1;
            }
        }
        print_r($index1);
        print_r($index2);
    }
?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="#" method="post">
        <input type="checkbox" name="menu[][]">1<br>
        <input type="checkbox" name="menu[][]">2<br> 
        <input type="checkbox" name="menu[][]">3<br>
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>