繁体   English   中英

php类中的多维数组打印

[英]multidimentional array printing in a php class

有一个FPDF类,我在类中传递一个数组,其名称为productList

$myclass->productList($table_rows);

该数组包含MySql表中的一些行

喜欢

Array (
[0] => Array ( [id] => 170 [product] => 10211 [qty] => 1 [price] => 50 )
[1] => Array ( [id] => 171 [product] => 10211 [qty] => 1 [price] => 50 ) 1

我正在使用一个额外的函数来解析数组,但它只显示第一行。 另外,它显示带有数据的表列名称

例如id1,data1 ## somedata

我想要的输出是

1,#somedata,#some 2,#somedata,#some

期望的输出图像:

所需的输出图像

当前输出图像:

当前输出图像

首先我发布数组打印功能

function makeNestedList(array $Array){
$w = array(90, 25, 20, 25,30);
foreach($Array as $Key => $Value){
    $Output = $Key;
    if(is_array($Value)){
        $Output .= $this->makeNestedList($Value);
    }else{
        $Output .= $Value;

    }
   //Product List
    $this->Cell($w[0],6,$Output,'LR',0,'L',1);
}

return $Output;
}

以及负责打印的产品清单功能

function productList($pdata)
{
//Function to print product table 

// Product Table Header
$header = array('Product', 'Qty', 'Rate', 'Discount','Subtotal'); 
//cell width $w
$w = array(90, 25, 20, 25,30);
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C',true);
$this->Ln();

// Product Data  <===== Here is problem

$this->makeNestedList($pdata);

// Closing line and extra
$this->Cell(array_sum($w),0,'','T');
$this->Ln();
}

经过长时间艰苦的尝试,我得到了这个简单的解决方案

//get $pdata
$this->productList($tablerows);


function productList($pdata)
{
and set a loop
foreach($table_rows as $key => $value)
{
$this->Cell($w[0],6,$value['product'],'LR',0,'L',$fill);
$this->Cell($w[1],6,$value['qty'],'LR',0,'C',$fill);
$this->Cell($w[2],6,$value['price'],'LR',0,'C',$fill);
$this->Cell($w[3],6,$value['discount'],'LR',0,'C',$fill);
$this->Cell($w[4],6,$value['subtotal'],'LR',0,'C',$fill);
$this->Ln();
$fill = !$fill;    
}

如果您的数组数据如下所示:

array (
            array ( 'product' => 10211, 'qty' => 1, 'rate' => 50, 'discount' => 50 , 'subtotal' => 50 ),
            array ( 'product' => 10212, 'qty' => 1, 'rate' => 100, 'discount' => 100 , 'subtotal' => 100 )
        );

该代码可能对您有用。 我看到您将数组的所有值连接到$Output并放入一个单元格中。 如果要生成表,则不应该这样做。

function makeNestedList(array $Array){
$w = array(90, 25, 20, 25,30);
    for ($i=0; $i < count($Array) ; $i++) { 
    $ii = 0;
        foreach ($Array[$i] as $key => $value) {
            $this->Cell($w[$ii],6,$Output,'LR',0,'L',1);
            $ii++;
        }
    }
}

暂无
暂无

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

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