Shark Shark - 1 year ago 54
PHP Question

How to iterate through $_POST arrays in PHP

I'm using the FPDF library and I'm trying to make a new cell dynamically. I have in my HTML a group of input fields all with the same name attribute that looks like this name="field[0][]". If the user generates a second group then their name attribute will look like this name="field[1][]" and so on. Here is the HTML:

<div class="new">
<input name="field[0][]" class="description" type="text" maxlength="255" placeholder="Enter Description" value=""/>
<input name="field[0][]" data-rate="rate" class="rate qty" type="text" maxlength="255" placeholder="0" size="5" value=""/>
<input name="field[0][]" data-price="price" class="pack price" type="text" maxlength="255" placeholder="$ 0.00" size="5" value=""/>
<input name="field[0][]" id="amount" class="amount" type="text">

In PHP I have a foreach loop that gets all the values from name="field[0][]" and inject them in a FPDF Cell, and here is my code.

$width_array = array(100, 25, 25, 0);
$pos_array = array(0, 0, 0, 1);
$align_array = array('L', 'C', 'L', 'L');

foreach ($_POST['field'][0] as $key => $description) {
$pdf->Cell($width_array[$key],10, "{$description}", 1, $pos_array[$key], $align_array[$key]);

So far this looks great for one set of inputs with the same name attribute but how can I generate more cells dynamically if I have more sets of inputs like example $_POST['field'][1], $_POST['field'][2] etc. I know if I add another foreach loop and change the array number it will show me the next fields but that is wrong,it has to be dynamically generated.

foreach ($_POST['field'][1] as $key => $description) {
$pdf->Cell($width_array[$key],10, "{$description}", 1, $pos_array[$key], $align_array[$key]);

Is it possible to add one to this $_POST['field'][0]? and then use it in the foreach loop ?

Answer Source

Is the problem PHP or HTML?

HTML you could solve through JS. Therefore you just need to save the index and every time someone adds a block you increase the index. By that you can create the HTML code dynamically.

PHP you simply need to put 2 foreachs in each other:

foreach ($_POST['field'] as $dataArray) {
    foreach ($dataArray as $key => $description) {
        $pdf->Cell($width_array[$key],10, "{$description}", 1, $pos_array[$key], $align_array[$key]);