dongyiyu882684 2016-11-17 18:04
浏览 78

如何在循环两个数组时防止重复输出

I am trying to loop through two arrays at once. the first array contains the headings, the second array contains the data the user has imputed via the form. these values are then set to a pdf file. the problem I am having is that the output is being duplicated twice.

current output

first name user input
first name user input
last name user input
last name user input

output that I 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 as &$value) {
        foreach ($_POST as $key => $data) {
            if($key == 'submit') {
                continue;
            }    

            $pdf->SetFont('Arial','B',16);
            $pdf->write(40,"$value");
            $pdf->write(40,"$data");
            $pdf->ln(10);
        }
    }
    $pdf->Output();
}
?>
  • 写回答

2条回答 默认 最新

  • dsmvovm27249 2016-11-17 18:28
    关注

    Firstly, this is unexpected behavior because the second loop should be repeated as first name, last name, first name, last name. (see what I mean here).

    $heading = ['first name', 'last name'];
    

    The above snippet of your code shows that you have 2 entries in your array. Therefore, your inner foreach() loop will be repeated twice since it is wrapped inside it. A better understanding:

    foreach(... as ...) // 2 entries
       foreach(... as ...) // 3 entries that will be repeated twice ^
    

    You can achieve this using Array index's with a counter.

    $i = 0; // index start at 0
    
    foreach($_POST as $k => $v) {
        if($k == "submit") continue;
    
        $pdf->write(40, $heading[$i++]);
        $pdf->write(40, $v);
        [...]
    }
    

    Hope this helped your duplication issue.
    tldr: See it working here.

    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000