简体   繁体   中英

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

I had tried to generate txt file from php foreach loop, it works but the result is not parallel like if used table here:

My expectation like this :

This is my code :

        $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);

Please someone help me.

Why don't you implement a function like this:

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

Then, any time you want to print a column, do it like this:

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

I'm assuming you want this printed to some kind of plain text file with a fixed width font. If you're doing something for the web, this is the wrong approach (you should use HTML for your formatting).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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