php - how to prevent duplicate outputs when looping through two arrays -
i trying loop through 2 arrays @ once. first array contains headings, second array contains data user has imputed via form. these values set pdf file. problem having output being duplicated twice.
current output
first name user input first name user input last name user input last name user input
output want
first name john last name smith
var dump
array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "submit" } array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "submit" } array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "submit" } array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "submit" }
code
<?php require('fpdf.php');?> <?php $headings = [ "first_name" => "first name", "last_name" => "last name", ]; if(isset($_post['submit'])) { $pdf = new fpdf(); $pdf->addpage(); foreach ($headings &$value) { foreach ($_post $key => $data) { if($key == 'submit') { continue; } $pdf->setfont('arial','b',16); $pdf->write(40,"$value"); $pdf->write(40,"$data"); $pdf->ln(10); } } $pdf->output(); } ?>
firstly, unexpected behavior because second loop should repeated first name, last name, first name, last name. (see mean here).
$heading = ['first name', 'last name'];
the above snippet of code shows have 2 entries in array. therefore, inner foreach()
loop repeated twice since wrapped inside it. better understanding:
foreach(... ...) // 2 entries foreach(... ...) // 3 entries repeated twice ^
you can achieve using array index's counter.
$i = 0; // index start @ 0 foreach($_post $k => $v) { if($k == "submit") continue; $pdf->write(40, $heading[$i++]); $pdf->write(40, $v); [...] }
hope helped duplication issue.
tldr: see working here.
Comments
Post a Comment