繁体   English   中英

php使用表格格式从txt文件生成foreach循环中的数据

[英]php generate data from foreach loop on txt file with table formatted

我曾尝试从php foreach循环生成txt文件,它可以工作,但结果不是平行的,如果在这里使用表:

我的期望是这样的:

这是我的代码:

        $output[] = ''."\n".'';
    $output[] = '  No  '.'                    Name Product                    '.'    Total   '."\n".'';
    foreach($query->result() as $row){
       $results = $row->id_product; 
       $product = $this->db->query("select product_name from master_product WHERE product_id='".$results."'");
       $product_name = $product->row()->product_name;
       $output[] = '  '.$no.str_repeat(" ",20).''. $product_name.str_repeat(" ",20).''.$row->quantity.'  '.$row->scale."\n".'';
       $no++;
    }
    file_put_contents(APPPATH."txt/test.txt", $output);

请有人帮助我。

为什么不实现这样的功能:

function padColumnText($text, $colWidth)
{
    if (strlen($text) > $colWidth)
    {
        return substr($text, 0, $colWidth);
    }
    return $text . str_repeat(" ", $colWidth - strlen($text));
}

然后,只要您想要打印列,就这样做:

output[] = padColumnText($no, 5) . padColumnText($product_name, 20) ...

我假设你想要打印到某种带有固定宽度字体的纯文本文件。 如果您正在为Web做某事,这是错误的方法(您应该使用HTML进行格式化)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM