fpdf - How to iterate through $_POST arrays in PHP

506

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 >
  <input name="field[0][]" type="text" maxlength="255" placeholder="Enter Description" value=""/>
  <input name="field[0][]" data-rate="rate" type="text" maxlength="255" placeholder="0" size="5" value=""/>
  <input name="field[0][]" data-price="price" type="text" maxlength="255" placeholder="$ 0.00" size="5" value=""/>
  <input name="field[0][]" id="amount" type="text">
</div>

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 ?

50

Answer

Solution:

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]);
    }
}

People are also looking for solutions to the problem: php - i can not figure out how to implement search engine into sql syntax

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.