如何创建动态数组变量

时间:2015-10-02 21:42:58

标签: php arrays

我有这些数组,我想通过创建一个动态变量来遍历每个数组,该变量将自己的名字自动放入foreach循环中

foreach ($activities.$i as &$activity) { //$i = 1,2,3,4..
   //code

}

//activities
$activities1 = $_POST["activities1"];
$activities2 = $_POST["activities2"];
$activities3 = $_POST["activities3"];
$activities4 = $_POST["activities4"];

1 个答案:

答案 0 :(得分:1)

更简单的方法是简单地使用数组命名hack:

<input name="activities[1]" ..>
<input name="activities[2]" ..>
<input name="activities[3]" ..>

使你成为$_POST['activities']数组:

foreach($_POST['activities'] as $i => $value) {
   // $i -> 1,2,3,4
}

但是如果你坚持将索引嵌入到密钥的名称中,那么:

foreach(range(1,4) as $i) {
    foreach($_POST["activities{$i}"] as $value) {
        ...
    }
}