使用foreach循环在PHP中动态地向二维数组添加值[关闭]

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.

I assume you are having some kind of array input in your form submission. If so you can try to to name the fields like this. It will give you a two dimensional array directly in the $_POST variable.

<input type="text" name="data[0][id]" />
<input type="text" name="data[0][gd]" />
<input type="text" name="data[0][q]" />
<input type="text" name="data[0][p]" />
<input type="text" name="data[0][t]" />

<input type="text" name="data[1][id]" />
<input type="text" name="data[1][gd]" />
<input type="text" name="data[1][q]" />
<input type="text" name="data[1][p]" />
<input type="text" name="data[1][t]" />

<input type="text" name="data[2][id]" />
<input type="text" name="data[2][gd]" />
<input type="text" name="data[2][q]" />
<input type="text" name="data[2][p]" />
<input type="text" name="data[2][t]" />

The $_POST array will look something like:

array(
  "data" => array(
    0 => array("id" => "value", "gd" => "value" ... ),
    1 => array("id" => "value", "gd" => "value" ... ),
    2 => array("id" => "value", "gd" => "value" ... ),
  )
)