If you use sql statements to do it, the workload will be too much, so I try to write a crosstab class by myself. Without further ado, let’s take a look at the code
Copy the code The code is as follows:
/**
* Basic Crosstab
* @author hugh
*
*/
class Pivot
{
private $HORIZONTAL_TOTAL_FIELD = 'total';
private $VERTICAL_TOTAL_FIELD = 'total';
private $data;
private $topPivot;
private $leftPivot;
private $measure;
private $hor izontalColumn = array ();
private $verticalColumn = array ();
private $pivotValue = array ();
private $isHorizontalTotal = true;
private $isVerticalTotal = true;
private $horizontalTotal = null;
private $verticalTotal = null ;
private $title = 'PivotTab';
/**
* Initialize crosstab
*/
private function InitPivot()
{
$this->topPivot;
foreach ( $this->data as $d )
{
$this->horizontalColumn [] = $d [$this->leftPivot];
$this->verticalColumn [] = $d [$this->topPivot];
}
$this-> horizontalColumn = array_unique ( $this->horizontalColumn );
$this->verticalColumn = array_unique ( $this->verticalColumn );
$reasult = array ();
foreach ( $this->horizontalColumn as $h )
{
foreach ( $this->verticalColumn as $v )
{
$this->pivotValue [$h] [$v] = 0;
}
}
}
/**
* Fill in data
* /
private function fillData()
{
foreach ( $this->data as $row )
{
$this->pivotValue [$row [$this->leftPivot]] [$row [$this- >topPivot]] += $row [$this->measure];
}
if ($this->isHorizontalTotal)
{
$this->setHorizontalTotal ();
}
if ($this- >isVerticalTotal)
{
$this->setVerticalTotal ();
}
}
/**
* Set vertical total
*/
private function setVerticalTotal()
{
$this->verticalColumn [] = $this- >VERTICAL_TOTAL_FIELD;
foreach ( $this->horizontalColumn as $i )
{
$rowsum = 0;
foreach ( $this->verticalColumn as $j )
{
$rowsum += $this-> pivotValue [$i] [$j];
}
$this->pivotValue [$i] [$this->TOTAL_FIELD] = $rowsum;
}
}
/**
* Set horizontal total
*/
private function setHorizontalTotal()
{
$this->horizontalColumn [] = $this->HORIZONTAL_TOTAL_FIELD;
foreach ( $this->verticalColumn as $i )
{
$rowsum = 0;
foreach ( $this- >horizontalColumn as $j )
{
$rowsum += $this->pivotValue [$j] [$i];
}
$this->pivotValue [$this->HORIZONTAL_TOTAL_FIELD] [$i] = $rowsum;
}
}
/**
* Rendering
*/
function Render()
{
echo '
';
print_r ( $this->pivotValue );
}
/**
* Render as table
*/
function RenderToTable()
{
$resault = "
$ this->title | n";$value | n";
$i | n";$value | n";
The above introduces the implementation code of arraynetworks PHP Array crosstab, including the content of arraynetworks. I hope it will be helpful to friends who are interested in PHP tutorials.