从一个foreach循环动态地在PHP中为二维数组添加值 [英] Add values to a two dimensional array dynamically in PHP from a foreach loop
问题描述
数组([id0] => id [gd0] = 50%[q 0] => 1 [p 0] => 10 [t 0] => 10 [id1] => id [gd1] => 65%[q1] => 2 [p1 ] => 20 [t1] => 40 [id2] => id [gd2] => 90%[q2] => 2 [p2] => 510 [t2] => 1020) b $ b
我想通过存储相同的值使它成为一个二维数组,像这样:数组(array([id0] => id [gd0] => 50%[q0] => 1阵列([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; //第一维的索引
$ Y = 0; //第二个索引
foreach($ _POST as $ val){
if($ val =='id'){
$ X ++;
$ Y = 0;
} else {
$ items [$ X] [$ Y] == $ val;
//增加第二个索引以防止覆盖
$ Y ++;
}
}
print_r($ items);
然而,这是行不通的。 print_r()
仅显示 Array()
==
而不是赋值运算符 =
in你的 else
语句。 I have the following array coming from a form submission:
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 )
I want to make it a two dimensional array by storing the same values, in a new pattern like so:
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))
Thus I'm trying to rearrange the similar information in a new dimension in an another array. I have tried a foreach loop, but with no luck:
$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);
However, it is not working. print_r()
displays only Array()
You are using the equality operator ==
rather than the assignment operator =
in your else
statement.
这篇关于从一个foreach循环动态地在PHP中为二维数组添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!