【发布时间】:2012-10-03 14:38:22
【问题描述】:
我有以下来自表单提交的数组:
Array ( [id0] => id [gd0] => 50% [q0] => 1 [p0] => 10 [t0] => 10 [id1] => id [gd1] => 65% [q1] => 2 [p1] => 20 [t1] => 40 [id2] => id [gd2] => 90% [q2] => 2 [p2] => 510 [t2] => 1020 )
我想通过存储相同的值使其成为一个二维数组,像这样的新模式:
Array (array([id0] => id [gd0] => 50% [q0] => 1 [p0] => 10 [t0] => 10 ) , array([id1] => id [gd1] => 65% [q1] => 2 [p1] => 20 [t1] => 40 ) , array([id2] => id [gd2] => 90% [q2] => 2 [p2] => 510 [t2] => 1020))
因此,我试图在另一个数组的新维度中重新排列相似的信息。我尝试了一个 foreach 循环,但没有运气:
$items = array();
$X = -1; // the index of the first dimension
$Y = 0; // the second index
foreach ($_POST as $val) {
if ($val == 'id') {
$X++;
$Y = 0;
} else {
$items[$X][$Y] == $val;
// increment the second index to prevent overwriting
$Y++;
}
}
print_r($items);
但是,它不起作用。 print_r() 仅显示 Array()
【问题讨论】:
-
如果您可以控制表单的 html,那么使用数组表示法可能是个好主意:
name="data[0][theKeyForTheField]",那么您就已经把所有东西都整理好了。
标签: php post loops multidimensional-array foreach