Foreach inside foreach than show it in HTML Table - php

Good day. I'm now trying to create detail that come from my sql table.
Here is My PHP:-
public function export()
{
$query = $this->input->cookie("cookie_invent_query");
$data['header'] = $this->modelmodel->showdata($query);
foreach($data['header'] as $header){
$data['detail'][] = $this->modelmodel->showdata("select * from DeliveryOrderDetail
where deliveryordertransno = '".$header->TransactionNo."' ");
}
echo "<pre>"; print_r($data['detail']);
$this->load->view("do_mutasi/export",$data);
}
with my script above i get tis in print_r()
result from $data['header']
Array
(
[0] => stdClass Object
(
[FinalReleaseStatus] => 1
[DeliveryOrderDate] => 2016-12-21 17:25:18.487
[TransactionNo] => DO-DL-K-LFKG-11
[DocumentNo] => DOZZ-DL-K-LFKG-6
[ToCustomerCode] => AFF004
[CategoryCode] => ZZ
[ETADate] => 2016-12-21 17:25:18.487
)
)
result from $data['detail']
Array
(
[0] => Array
(
[0] => stdClass Object
(
[TransactionNo] => DOD-DL-K-LFKG-9
[LineNo] => 1000
[ItemCode] => FA00000111
[DeliveryOrderTransNo] => DO-DL-K-LFKG-11
[ExtraRemark] => 0
[ExtraRemark2] => 0
[Quantity] => 3.00000000000000000000
[UOMCode] => PCS
[CreatedDate] => 2016-12-21 17:26:25.063
[CreatedBy] => boby
[ModifiedDate] => 2016-12-21 17:26:25.063
[ModifiedBy] =>
)
)
)
then after i send it to my view and this what i can do for now
<?php foreach($header as $hdr) { ?>
Header
<table class="table">
<thead>
<tr>
<th>Trnsaction No</th>
<th>Document No</th>
<th>To Customer</th>
<th>Delivery Order Date</th>
</tr>
</thead>
<tbody>
<td><?=$hdr->TransactionNo;?></td>
<td><?=$hdr->DocumentNo;?></td>
<td><?=$hdr->ToCustomerCode;?></td>
<td><?=$hdr->DeliveryOrderDate;?></td>
</tbody>
</table>
Detail
<table>
<thead>
<tr>
<th>Transaction No</th>
<th>Item Code</th>
<th>Quntity</th>
<th>Uom Code</th>
</tr>
</thead>
<tbody>
<?php
foreach($detail as $rsltdt =>$key) { ?>
<tr>
<td><?=$rsltdt['TransactionNo'];?></td>
<td><?=$rsltdt['ItemCode'];?></td>
<td><?=$rsltdt['Quantity'];?></td>
<td><?=$rsltdt['UOMCode'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
Asyou can see. I loop the detail inside the header loop. Because in some records there are multiple detail. I loop the header because i want to show it multiple records not just one record
here is the result so far
I can't show detail. So my question is. How can i show the detail depends on header.
[TransactionNo] = [DeliveryOrderTransNo]

Check once:-
foreach($detail as $rsltdt) {
foreach ($rsltdt as $rsl){ ?>
<tr>
<td><?=$rsl->TransactionNo;?></td>
<td><?=$rsl->ItemCode;?></td>
<td><?=$rsl->Quantity;?></td>
<td><?=$rsl->UOMCode;?></td>
</tr>
<?php } } ?>

It is better to put all details in its corresponding header :
public function export()
{
$query = $this->input->cookie("cookie_invent_query");
$data['header'] = $this->modelmodel->showdata($query);
foreach($data['header'] as $header){
$data['header']['details'] = $this->modelmodel->showdata("select * from DeliveryOrderDetail
where deliveryordertransno = '".$header->TransactionNo."' ");
}
}
then you can simply write the second loop :
foreach($hdr['details'] as $rsltdt) { ?>
<tr>
<td><?=$rsltdt->TransactionNo;?></td>
<td><?=$rsltdt->ItemCode;?></td>
<td><?=$rsltdt->Quantity;?></td>
<td><?=$rsltdt->UOMCode;?></td>
</tr>
<?php } ?>
You don't need to nest the details array anymore :
put:
$data['header']['details'] = $this->modelmodel->showdata("select * f....
instead of:
$data['header']['details'][] = $this->modelmodel->showdata("select * f....

Related

Convert scraping result into an array

I am scraping a website using Simple HTML DOM, the output looks like this:
<tr>
<th>Satuan</th>
<th>Harga Barang 1</th>
<th>Harga Barang 2</th>
<th>Harga Barang 3</th>
<th>Harga Barang 4</th>
</tr>
<tr>
<td>0.5</td>
<td>Rp 388.000</td>
<td>Rp 342.000</td>
<td>Rp 456.000</td>
<td>Rp 377.000</td>
</tr>
<tr>
<td>1.0</td>
<td>Rp 725.000</td>
<td>Rp 676.000</td>
<td>Rp 855.000</td>
<td>Rp 684.000</td>
</tr>
and this is my code:
<?php
include('simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file("mylink.com/blabla");
foreach($html->find('tr') as $e) {
echo $e;
}
?>
How to convert the output into arrays?
Here is the snippet,
$ret = $html->find('tr');
$i = true;
$headers = [];
foreach ($ret as $key => $value) {
if ($i) {
// fetching headers of first row
foreach ($value->find('th') as $cell) {
$headers[] = $cell->plaintext;
}
} else {
$temp = [];
// fetching pending values of td
foreach ($value->find('td') as $cell) {
$temp[] = $cell->plaintext;
}
// combining headers with values fetched from not first row
$result[] = array_combine($headers, $temp);
}
$i = false;
}
print_r($result);die;
Output
Array
(
[0] => Array
(
[Satuan] => 0.5
[Harga Barang 1] => Rp 388.000
[Harga Barang 2] => Rp 342.000
[Harga Barang 3] => Rp 456.000
[Harga Barang 4] => Rp 377.000
)
[1] => Array
(
[Satuan] => 1.0
[Harga Barang 1] => Rp 725.000
[Harga Barang 2] => Rp 676.000
[Harga Barang 3] => Rp 855.000
[Harga Barang 4] => Rp 684.000
)
)

Get json array response and store in another array

I have cURL function which make calls to api based on ID which I provide and return data in array. So far everything works perfectly. What I want and can't figure out is this:
I have foreach which display in table all orders lie
#foreach($orders as $order)
$order->address
$order->time_created
$order->price
... etc
#endforeach
Is it possible to put this cURL inside the foreach and add on each row based on $order->order_id to show some more data from the array?
So something like this
#foreach($orders as $order)
$order->address
$order->time_created
$order->price
... etc
$url = get_curl_content_tx("http://example.com/".$order->order_id);
$data = json_decode($url,true);
#foreach ( $data as $moreData )
#if ( $moreData['data'] == $order->time_created )
// show something
#else
// show other thing
#endif
#endforeach
#endforeach
My problem is that I can't figure how to loop the url so I can get all orders_id i.e.
$url = get_curl_content_tx("http://example.com/1");
$url = get_curl_content_tx("http://example.com/2");
$url = get_curl_content_tx("http://example.com/3");
$url = get_curl_content_tx("http://example.com/4");
$url = get_curl_content_tx("http://example.com/5");
$url = get_curl_content_tx("http://example.com/6");
So then I can perform my if/else block. Framework which I use is Laravel 4.2.
Hope it is clear enough what I want to accomplish. If is not I will try to clear things..
EDIT: Example what it should be:
<table>
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">Date Created</th>
<th class="text-center">Name</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<th>$url = get_curl_content_tx("http://example.com/1")</th>
<th>Product 1</th>
</tr>
<tr>
<th>2</th>
<th>$url = get_curl_content_tx("http://example.com/2")</th>
<th>Product 2</th>
</tr>
</tbody>
</table>
You can use laravel's unique method for collections to remove duplicate order id's before iterating them.
$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
Or you can use PHP method as well. How to remove duplicate values from a multi-dimensional array in PHP
I have manage to do it and will post it as answer. So since I already had ID's of the product I've made it like this directly in the blade. Maybe there is a room for improvements but for now at least it is working.
This is short version without echoes in conditions
<td class="text-center">
<?php
$url=get_curl_content_tx("http://example.com/". $order->order_id);
$arr = json_decode($url, true);
if (is_array($arr['data']) || is_object($arr['data'])) {
foreach($arr['data'] as $data ) {
$match = false;
if ($data['amount'] == $order->amount) {
$match = $data;
break;
}
}
if($match !== false ) {
if( .. ) {
// do something
}
else {
// do something else
}
}
else { }
}
?>
</td>

Slicing PHP Array Into Table

Not sure if "slice" is the right word.. however I have the following array stored in a variable.
Array (
[0] => Design|1-cylinder 4-stroke engine, water-cooled
[1] => Displacement|373.2 cm³
[2] => Bore|89 mm
[3] => Stroke|60 mm
[4] => Performance|32 kW (43 hp)
[5] => Starting aid|Electric starter
[6] => Transmission|6 speed, claw shifted
[7] => Engine lubrication|Wet sump
) 1
Note the "|"'s that are separating the content. This content should be in a table like this.
<table>
<thead>
<tr>
<td>Title</td>
<td>Details</td>
</tr>
</thead>
<tbody>
<tr>
<td>Engine Displacement</td>
<td>373.2 cm³</td>
</tr>
<tr>
<td>Transmission</td>
<td>6 speed, claw shifted</td>
</tr>
</tbody>
</table>
How can I write a foreach statement that would do this? I am not even sure where to start? Should I separate the arrays? Not sure.
Thanks in advance!
$aData = array(
'Design|1-cylinder 4-stroke engine, water-cooled',
'Displacement|373.2 cm³',
'Bore|89 mm',
'Stroke|60 mm',
'Performance|32 kW (43 hp)',
'Starting aid|Electric starter',
'Transmission|6 speed, claw shifted',
'Engine lubrication|Wet sump'
);
?>
<table>
<thead>
<tr>
<th>Title</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<?php
$iCountData = count( $aData );
for( $i = 0; $i < $iCountData; ++$i )
{
$aTmp = explode( '|', $aData[ $i ] );
echo '<tr>';
echo '<td>';
echo $aTmp[ 0 ];
echo '</td>';
echo '<td>';
echo $aTmp[ 1 ];
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>

how to show data from document to index.phtml in zf2?

i make index action in which i want to get data of calender and show this data using index.phtml but always no calendar shown,how i show calendar data?
here is my indexaction:
public function indexAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$qb = $dm->createQueryBuilder('Calendar\Document\Calendar')->select('title', 'description');
$query = $qb->getQuery();
$calendars = $query->execute();
return array('calendars' => $calendars);
}
and here is my index.phtml:
<?php
$calendars = $this->calendars;
$title = 'Calendars by '.$this->escapeHtml($calendars[0]->email);
$this->headTitle($title);
?>
<h3><?php echo $this->escapeHtml($title); ?></h3>
<ul>
<li>Create New Calendar</li>
</ul>
<h4>Calendars created by you</h4>
<?php if (is_null($calendars)): ?>
<p>No calendars</p>
<?php else: ?>
<table class="table">
<tr>
<th>calendar name</th>
<th>description</th>
<th>owner</th>
<th>actions</th>
</tr>
<?php foreach ($calendars as $calendar) : ?>
<tr>
<td>
<a href="<?php echo $this->url('calendar',array('action'=>'show', 'id' => $calendar->calendar_id));?>">
<?php echo $this->escapeHtml($calendar->title);?>
</a>
</td>
<td><?php echo $this->escapeHtml($calendar->description);?></td>
<td>
<?php echo $this->gravatar($this->escapeHtml($calendar->email));?>
<?php echo $this->escapeHtml($calendar->email);?>
</td>
<td>
<a href="<?php echo $this->url('calendar',
array('action'=>'settings', 'id' => $calendar->calendar_id));?>">Settings</a>
<a href="<?php echo $this->url('calendar',
array('action'=>'delete', 'id' => $calendar->calendar_id));?>">delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
and here is my response:
Doctrine\ODM\MongoDB\Cursor Object
(
[baseCursor:Doctrine\ODM\MongoDB\Cursor:private] => Doctrine\MongoDB\Cursor Object
(
[connection:protected] => Doctrine\MongoDB\Connection Object
(
[mongo:protected] => MongoClient Object
(
[connected] => 1
[status] =>
[server:protected] =>
[persistent:protected] =>
)
[server:protected] => mongodb://127.0.0.1:27017/events
[options:protected] => Array
(
)
[config:protected] => Doctrine\ODM\MongoDB\Configuration Object
(
[attributes:protected] => Array
(
[mongoCmd] => $
[retryConnect] => 0
[retryQuery] => 0
[autoGenerateProxyClasses] => 1
[proxyDir] => data/DoctrineMongoODMModule/Proxy
[proxyNamespace] => DoctrineMongoODMModule\Proxy
[autoGenerateHydratorClasses] => 1
[hydratorDir] => data/DoctrineMongoODMModule/Hydrator
[hydratorNamespace] => DoctrineMongoODMModule\Hydrator
[defaultDB] => events
[metadataCacheImpl] => Doctrine\Common\Cache\ArrayCache Object
(
[data:Doctrine\Common\Cache\ArrayCache:private] => Array
how i show data on index page?
You need a view model to render your data. Instead of
return array('calendars' => $calendars);
You want this for a View:
$viewModel = new ViewModel
(
array
(
'calendars' => $calendars,
)
);
return $viewModel;
or this for Json:
$jsonModel = new JsonModel
(
array
(
'calendars' => $calendars,
)
);
return $jsonModel;
make sure to add the use statements for your controller:
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
If you want to specify a specific view you can use:
$viewModel->setTemplate('path/to/specific/view.phtml');
or
$viewModel->setTemplate('mapping/for/specifc/view');
with the mapping specified in your module config

Using rowspan with array output to table in php

I'm looking to modify a table on a page to include merged rows.
Here is the php code that deals with the output from a mysql db:
######## PRINT OUT TABLE WITH YEARS AND OFFICES PLUS NAMES IN CELLS ########
for ($y = $year_max; $y >=$year_min; $y--){
echo '<tr><th>'.$y.'</th>';
for ($i = 0; $i<count($offices_used); $i++){
if (isset($data[$y][$offices_used[$i]])){
echo '<td>'.$data[$y][$offices_used[$i]].'</td>';
} // END IF
else {
echo '<td></td>';
} // END ELSE
} echo '</tr>';
} // END FOR
The table further below is generated from a multidimensional array such as immediately below;
array (
[2013] => Array
(
[President] => John Mills
[Internal VP] => Virgil Bagdonas
[External VP] => Reid Gilmore
[Treasurer] => Todd Heino
[Secretary] => Eric Holmquist
[Newsletter] => Art Bodwell
[Webmaster] => Dave Eaton
[Photographer] => Rick Angus
[Video Librarian] => Mike Peters
[Store Manager] => Kevin Nee
)
[2012] => Array
(
[President] => Dave Eaton
[Internal VP] => Jim Metcalf
[External VP] => Reid Gilmore
[Treasurer] => Mike Peters
[Secretary] => Eric Holmquist
[Newsletter] => Art Bodwell
[Webmaster] => Dave Eaton
[Photographer] => Peter Wilcox
[Video Librarian] => Ray Asselin
[Store Manager] => Joe Giroux
)
[2011] => Array
(
[President] => Charlie Croteau
[Internal VP] => Reid Gilmore
[External VP] => Rick Angus
[Treasurer] => Mike Peters
[Secretary] => Eric Holmquist
[Newsletter] => Ron Rocheleau
[Webmaster] => Dave Eaton
[Photographer] => Peter Wilcox
[Video Librarian] => Ray Asselin
[Book Librarian] => Roger Boisvert
[Store Manager] => Mike Smith
)
...etc
My php code NOW generates this table from mysql db:
<tr>
<th>Year</th>
<th>President</th>
<th>Internal VP</th>
<th>External VP</th>
<th>Treasurer</th>
<th>Secretary</th>
<th>Webmaster</th>
<th>Newsletter</th>
<th>Photographer</th>
<th>Video Librarian</th>
<th>Book Librarian</th>
<th>Store Manager</th>
</tr>
<tr>
<th>2013</th>
<td>John Mills</td>
<td>Virgil Bagdonas</td>
<td>Reid Gilmore</td>
<td>Todd Heino</td>
<td>Eric Holmquist</td>
<td>Dave Eaton</td>
<td>Art Bodwell</td>
<td>Rick Angus</td>
<td>Mike Peters</td>
<td></td>
<td>Kevin Nee</td>
</tr>
<tr>
<th>2012</th>
<td>Dave Eaton</td>
<td>Jim Metcalf</td>
<td>Reid Gilmore</td>
<td>Mike Peters</td>
<td>Eric Holmquist</td>
<td>Dave Eaton</td>
<td>Art Bodwell</td>
<td>Peter Wilcox</td>
<td>Ray Asselin</td>
<td></td>
<td>Joe Giroux</td>
</tr>
<tr>
<th>2011</th>
<td>Charlie Croteau</td>
<td>Reid Gilmore</td>
<td>Rick Angus</td>
<td>Mike Peters</td>
<td>Eric Holmquist</td>
<td>Dave Eaton</td>
<td>Ron Rocheleau</td>
<td>Peter Wilcox</td>
<td>Ray Asselin</td>
<td>Roger Boisvert</td>
<td>Mike Smith</td>
</tr>
But I WOULD LIKE to modify the array handling output to get the following:
<tr>
<th>Year</th>
<th>President</th>
<th>Internal VP</th>
<th>External VP</th>
<th>Treasurer</th>
<th>Secretary</th>
<th>Webmaster</th>
<th>Newsletter</th>
<th>Photographer</th>
<th>Video Librarian</th>
<th>Book Librarian</th>
<th>Store Manager</th>
</tr>
<tr>
<th>2013</th>
<td>John Mills</td>
<td>Virgil Bagdonas</td>
<td rowspan= "3">Reid Gilmore</td>
<td>Todd Heino</td>
<td rowspan="3">Eric Holmquist</td>
<td rowspan="9">Dave Eaton</td>
<td rowspan="2">Art Bodwell</td>
<td>Rick Angus</td>
<td>Mike Peters</td>
<td></td>
<td>Kevin Nee</td>
</tr>
<tr>
<th>2012</th>
<td>Dave Eaton</td>
<td>Jim Metcalf</td>
<td rowspan="2">Mike Peters</td>
<td>Peter Wilcox</td>
<td rowspan="3">Ray Asselin</td>
<td></td>
<td>Joe Giroux</td>
</tr>
<tr>
<th>2011</th>
<td>Charlie Croteau</td>
<td>Rick Angus</td>
<td>Ron Rocheleau</td>
<td>Peter Wilcox</td>
<td>Roger Boisvert</td>
<td>Mike Smith</td>
</tr>
Any leads on how to add a flag or counter to accomplish this is welcome. Thanks!
try this hope to work.(because I have not run it but think should work).
CODE for colspan:
for ($y = $year_max; $y >=$year_min; $y--){
echo '<tr><th>'.$y.'</th>';
$lastVal='';
$buf=array();
for ($i = 0; $i<count($offices_used); $i++){
(!isset($data[$y][$offices_used[$i]])?($data[$y][$offices_used[$i]]=''):'');// Im not sure that is really needed
if($lastVal==$data[$y][$offices_used[$i]]){
$buf[count($buf)-1]['rep']++;
}else{
$lastVal=$data[$y][$offices_used[$i]];
$buf[]=array('data'=>$lastVal,'rep'=>1);
}
foreach($buf as $arr){
echo '<td'.($arr['rep']>1?' colspan="'.$arr['rep'].'"':'') . '>'.$arr['data'].'</td>';
}
} echo '</tr>';
} // END FOR
NOTICE: error of code corrected
CODE for rowspan:(I think it can be down easier than this. bur I have tried to be good).
$buf=array();
for ($i = 0; $i<count($offices_used); $i++){// this loop makes fill $buf
$lastVal='';
for ($y = $year_max; $y >=$year_min; $y--){
(!isset($data[$y][$offices_used[$i]])?($data[$y][$offices_used[$i]]=''):'');// Im not sure that is really needed
if($lastVal==$data[$y][$offices_used[$i]]){
$buf[$i][count($buf[$i])-1]['rep']++;
}else{
$lastVal=$data[$y][$offices_used[$i]];
$buf[$i][$year_max-$y]=array('data'=>$lastVal,'rep'=>1);
}
}
}
$mtemp=$year_max;
foreach($buf as $row){
echo '<tr><th>'.$mtemp.'</th>';
foreach($row as $rec){
echo '<td'.($rec['rep']>1?' rowspan="'.$rec['rep'].'"':'') . '>'.$rec['data'].'</td>';
}
$mtemp--;
echo '</tr>';
}
really hope to work.
NOTICE: corrected
Solved by using:
############################################################################
######## PRINT OUT TABLE WITH YEARS AND OFFICES PLUS NAMES IN CELLS ########
for ($y = $year_max; $y >=$year_min; $y--){ // Loop through years
echo '<tr><th>'.$y.'</th>';
for ($i = 0; $i<count($offices_used); $i++){
if (isset($data[$y][$offices_used[$i]])){
$rowz =1;
if(!($data[$y][$offices_used[$i]] == $data[($y+1)][$offices_used[$i]])){
while ($data[$y][$offices_used[$i]] == $data[($y-$rowz)][$offices_used[$i]]) $rowz ++;
echo '<td rowspan = "'.$rowz.'">'.$data[$y][$offices_used[$i]].'</td>';
}
} // END IF
else {
echo '<td align = "center"> - </td>';
} // END ELSE
} echo '</tr>'; // End row of current year
} // END FOR Loop through years
echo '</table>';
See http://jsfiddle.net/eaton9999/8gMVK/ for resultant output page.
Thanks again to imsiso and other who helped!
I wrote a library a few days ago that can handle this stuff..
Have a look at https://github.com/donquixote/cellbrush
The benefit of the library is that you don't need to think about the order of cells in html, and which cells need to be skipped due to rowspan or colspan. Instead, you can just "paint" a cell anywhere in the grid, with whichever rowspan or colspan you want. And instead of specifying a number for rowspan or colspan, you simply specify the first and last row and column names of the rospan/colspan region.
E.g.
$table->td(['2011', '2013'], 'Secretary', 'Eric Holmquist');
Below is some code that creates the table you were asking for, with the help of this library. You still need some logic to calculate the intervals, but at least you don't need to worry about the integrity of the table html.
(This question is quite old, but there might still be people running into it from Google. So I hope it might be useful.)
<?php
require_once __DIR__ . '/vendor/autoload.php';
$data = array(
'2013' => array(
'President' => 'John Mills',
'Internal VP' => 'Virgil Bagdonas',
'External VP' => 'Reid Gilmore',
'Treasurer' => 'Todd Heino',
'Secretary' => 'Eric Holmquist',
'Newsletter' => 'Art Bodwell',
'Webmaster' => 'Dave Eaton',
'Photographer' => 'Rick Angus',
'Video Librarian' => 'Mike Peters',
'Store Manager' => 'Kevin Nee',
),
'2012' => array(
'President' => 'Dave Eaton',
'Internal VP' => 'Jim Metcalf',
'External VP' => 'Reid Gilmore',
'Treasurer' => 'Mike Peters',
'Secretary' => 'Eric Holmquist',
'Newsletter' => 'Art Bodwell',
'Webmaster' => 'Dave Eaton',
'Photographer' => 'Peter Wilcox',
'Video Librarian' => 'Ray Asselin',
'Store Manager' => 'Joe Giroux',
),
'2011' => array(
'President' => 'Charlie Croteau',
'Internal VP' => 'Reid Gilmore',
'External VP' => 'Rick Angus',
'Treasurer' => 'Mike Peters',
'Secretary' => 'Eric Holmquist',
'Newsletter' => 'Ron Rocheleau',
'Webmaster' => 'Dave Eaton',
'Photographer' => 'Peter Wilcox',
'Video Librarian' => 'Ray Asselin',
'Book Librarian' => 'Roger Boisvert',
'Store Manager' => 'Mike Smith',
),
);
// Collect positions to build table columns.
$positions = [];
foreach ($data as $year => $yearData) {
foreach ($yearData as $position => $person) {
$positions[$position] = TRUE;
}
}
$positions = array_keys($positions);
// Define table columns.
$table = (new \Donquixote\Cellbrush\Table())
->addColName('year')
->addColNames($positions)
;
// Create thead section.
$headRow = $table->thead()->addRow('head');
$headRow->th('year', 'Year');
foreach ($positions as $position) {
$headRow->th($position, $position);
}
// Create table rows with labels based on year.
$years = array_keys($data);
$table->addRowNames($years);
foreach ($years as $year) {
$table->th($year, 'year', $year);
}
// Fill table cells in each column.
foreach ($positions as $position) {
$periodPerson = NULL;
$periodFirstYear = NULL;
$periodLastYear = NULL;
$column = $table->colHandle($position);
foreach ($years as $year) {
$person = isset($data[$year][$position])
? $data[$year][$position]
: '-';
if (!isset($periodFirstYear)) {
// First year.
$periodFirstYear = $year;
}
elseif ($person !== $periodPerson) {
// Add a table cell with rowspan.
$column->td([$periodFirstYear, $periodLastYear], $periodPerson);
$periodFirstYear = $year;
}
$periodPerson = $person;
$periodLastYear = $year;
}
if (isset($periodFirstYear)) {
// Add a table cell with rowspan.
$column->td([$periodFirstYear, $periodLastYear], $periodPerson);
}
}
print $table->render();

Categories