Undefined variable : invites in yii view - php

This is my view code
<?php
Yii::import('common.extensions.chartjs.assets.js.*');
echo $eventdata['event_name']."<br>";
echo $contribution = Event::model()->contribution($eventdata['id'])."<br>";
echo $percentage = ($contribution/$eventdata['funding_goal_amount'])*100;
echo "<br>".Event::model()->dayleft($eventdata['id'])."<br>";
if($invites) {
$sms = 0;
$email = 0;
$totalinvites = count($invites);
foreach ($invites as $key => $data) {
if($data['type'] == 3) {
++$sms;
}
if($data['type'] == 1) {
++$email;
}
}
//gets the last 30 days
$d = array();
for($i = 0; $i < 28; $i++)
$d[] = date("d", strtotime('-'. $i .' days'));
$data=array(
);
$con=0;
foreach ($d as $key => $value) {
echo($value);
echo("<br>");
if($con==1)
{
die;
}
$data[]=callinvites($value);
}
echo(var_dump($data));
echo "Total invites are $totalinvites <br>";
echo "Invites by sms are $sms <br>";
echo "Invites by email are $email <br>";
}
echo "Google analytic api to come here <br>";
echo Event::model()->peopleContributed($eventdata['id'])."<br>";
if($contributors) {
foreach ($contributors as $key => $data) {
echo $data['fname']."<br>";
}
}
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {title:'Sales',minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div">
</div>
<div class="visits">
<?php
$this->widget('common.extensions.HZL.google.HzlVisualizationChart', array('visualization' => 'AreaChart',
'data' => array(
array('day', 'Hours per Day'),
array('Work', 11),
array('Eat', 2),
array('Commute', 2),
array('Watch TV', 2),
array('Sleep', 7)
),
'options' => array('title' => 'INVITES')));
?>
</div>
<?php
function callinvites($date)
{
$today_date=date('d');
$month=date('m');
echo $month;
$year=date('y');
if($date>$today_date)
{
if($month=='01')
{
$month='12';
}
else
{
$month=$month-1;
}
if($month=='12')
{
$year=$year-1;
}
}
$count=0;
$count_email=0;
$count_mobile=0;
foreach ($invites as $key => $value) {
$date2=new DateTime($value["created"]);
$date1=$date2->format('d');
$year1=$date2->format('y');
$month1=$date2->format('m');
if($date1==$date && $year1==$year && $month==$month1)
{
$count=$count + 1;
}
if($date1==$date && $year1==$year && $month==$month1 && $value["type"]=='1')
{
$count_email=$count_email+1;
}
if($date1==$date && $year1==$year && $month==$month1 && $value["type"]=='3')
{
$count_mobile=$count_mobile+1;
}
}
return array($date,$count,$count_email,$count_mobile);
}
?>
I get an error when I call the function callinvites and says undefined variable : invites in yii view
Although I used this
echo(var_dump($invites));
this shows an array of size 20 having values from the database, so why is the error happening?

In your callinvites function try changing this line
foreach ($invites as $key => $value) {
to
foreach ($this->invites as $key => $value) {

Related

PHP - Make nested if statement output shorter

I often end up with something like below:
<?php
foreach($items as $item) {
if($item['key']) {
echo 'Alright';
if($item['value']) {
echo 'Inside';
} else {
$output[] = [
$item['data1'],
$item['data2'],
];
}
} else {
$output[] = [
$item['data1'],
$item['data2'],
];
}
}
print_r($output);
As you can see I use nested if statements. What nags me is that I have the same output in both else. I would prefer keep things DRY.
So, if I'm in an else statement anywhere within the foreach, I want to output the same results.
Update
My real code is a bit more complex.
foreach($out as $i => $data) {
$dayshort = mb_substr($data[0], 0, 3);
if(isset($out[$i+1][0])) {
$future = $out[$i+1][0];
$daykey = array_search($data[0], $weekdays);
$nextday = $weekdays[$daykey + 1];
if($nextday != $future) {
$backkey = array_search($future, $weekdays) - 1;
$backname = mb_substr($weekdays[$backkey], 0, 3);
$final[] = [
$dayshort . ' - ' . $backname,
$data[1],
$data[2]
];
} else {
$final[] = [
$data[0],
$data[1],
$data[2]
];
}
} else {
$final[] = [
$data[0],
$data[1],
$data[2]
];
}
}
Now I've setup a repo here with the complete code: https://github.com/jenstornell/daybreaker
foreach($out as $i => $data) {
$dayshort = mb_substr($data[0], 0, 3);
$result = $data[0]; /* default case value */
if (isset($out[$i + 1][0])) {
$future = $out[$i + 1][0];
$daykey = array_search($data[0], $weekdays);
$nextday = $weekdays[$daykey + 1];
if ($nextday != $future) {
$backkey = array_search($future, $weekdays) - 1;
$backname = mb_substr($weekdays[$backkey], 0, 3);
$result = $dayshort.' - '.$backname; /* overrite here */
}
}
/* just once */
$final[] = [
$result,
$data[1],
$data[2]
];
}
I think it's more simpler
<?php
foreach($items as $item) {
if($item['key']) {
echo 'Alright';
if($item['value'])
echo 'Inside';
}
$output[] = [
$item['data1'],
$item['data2'],
];
}
You can initialize a variable for else part like
$is_false=0;
Set it to "1" once you are in else block and at last step check this variable and if it is "1" set the outout or else block code.
Refer the code below.
<?php
foreach($items as $item) {
if($item['key']) {
echo 'Alright';
if($item['value']) {
echo 'Inside';
} else {
$is_false = 1;
}
}else{
$is_false = 1;
}
if($is_false==1){
$output[] = [
$item['data1'],
$item['data2'],
];
}
}
print_r($output);

how to display multi dimension with 2 array and multiply it

This is the code to display multi dimension with array
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$numberArray = array(
array(1, 2, 3, 4, 7, 6),
array(2, 3, 1, 0, 5)
);
function printTable($numberArray) {
// Placeholder
$result = [];
// Setup the multiplication
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// Loop through the $result array and display the table
echo "<table border='1'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
Example of output: https://gyazo.com/2a0a5c07ac75f285f6b8a4631d5b723c
How to display the multi dimension with array and inside the answer will be multiply between numbers.
Looking at the links to the screenshots you provided, maybe this setup can help you:
<?php
$numberArray = array(
array(1, 2, 3, 4, 7, 6),
array(2, 3, 1, 0, 5)
);
function printTable($numberArray)
{
// Placeholder
$result = [];
// Setup the multiplication
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// Loop through the $result array and display the table
echo "<table border='2'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}

Algorithm to visualise data (multidimensional scaling?) in PHP project

I have small matrix of +-100 points/values, results of test and their distances (0-10, 10 is the closest) to each other: http://vis.arcs.cz.
I would like to visualize it in 2D to quickly find a groups of close values. So I need to process this matrix and get the coordinates of points in 2D.
The way is propably multidimensional scaling but I wasnt able to find an algorithm, library or extension nor use the math formulas into PHP code.
Im googling last two days and the closest results of it is
http://www.php.net/manual/en/lapack.leastsquaresbysvd.php - ?
(cant share more links as novice)
I'll be grateful for any solution applicable in php project (compiled MathLab code in C++...).
index.php:
<?php
require("data.php");
require("Mds.php");
$mds = new Mds();
$mds->prepareData($data);
//cislo udava pocet iteraci algoritmu,
//idealne by melo mit hodnotu pocetUzlu na druhou, prakticky muze byt o dost mensi, 5 az 10 krat pocet uzlu.
$mds->scale(100);
//mira splneni podminek - vraci cislo < mensi nez 1. Cim blizsi k 1, tim lepe vyhovuji vzdalenosti
//z vypocteneho rozlozeni zadanym vzdalenostem.
//v nemetrickych datech ovsem dochazi rychle k poklesu az do zapornych hodnot, protoze ve 2D neexistuje
//pro nektere body zadne spravne misto.
echo $mds->getRSquared();
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "MDS",
fontFamily: "arial black",
fontColor: "black"
},
axisX: {
title:"",
titleFontFamily: "arial"
},
axisY:{
title: "",
titleFontFamily: "arial",
titleFontSize: 12
},
data: [
{
type: "scatter",
toolTipContent: "<span style='"'color: {color};'"'><strong>{name}</strong></span> x: {y}, y: {y}",
dataPoints:
<?php
echo $mds->printCoords('{x: %X, y: %Y, name: "%LABEL"}');
?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 600px; width: 600px;">
</div>
mds.zip
</body>
</html>
data.php:
$data = array(
array ("Jablko", "Voda", 2),
array("Jablko", "Ohen", 7),
array("Jablko", "Cervena", 3),
array("Jablko", "Zelena", 2),
array("Voda", "Ohen", 8),
array("Voda", "Cervena", 8),
array("Voda", "Zelena", 2),
array("Ohen", "Cervena", 1),
array("Ohen", "Zelena", 5),
array("Cervena", "Zelena", 3)
);
Mds.php:
<?php
class Mds {
//node - pole tvaru [[x, y, label], ...]
public $nodes = array();
//tvaru [source][target]=distance
public $givenDistances = array();
public $currentDistances = array();
public function prepareData($data) {
$nodesMap = array();
$xxxx = 10000;
$xxx= 1000;
// $xxxx = 5000;
// $xxx = 600;
foreach($data as $link) {
$source = $link[0];
$target = $link[1];
if(!isset($nodesMap[$source])) {
$nodesMap[$source] = true;
$this->nodes[]=array((float) rand(1,$xxxx) / $xxx, (float) rand(1,$xxxx) / $xxx, $source);
}
if(!isset($nodesMap[$target])) {
$nodesMap[$target] = true;
$this->nodes[]= array((float) rand(1,$xxxx) / $xxx, (float) rand(1,$xxxx) / $xxx, $target);
}
}
//vytvori matici pro ulozeni vzdalenosti
foreach($this->nodes as $node) {
$this->givenDistances[$node[2]] = array();
$this->currentDistances[$node[2]] = array();
}
foreach($data as $link) {
$source = $link[0];
$target = $link[1];
$distance = $link[2];
$this->givenDistances[$source][$target] = $distance;
$this->givenDistances[$target][$source] = $distance;
}
}
protected function countCurrentDistances() {
$mean = 0;
$i = 0;
foreach($this->nodes as $nodeA) {
foreach($this->nodes as $nodeB) {
$dist = sqrt(($nodeB[0]-$nodeA[0])*($nodeB[0]-$nodeA[0]) + ($nodeB[1]-$nodeA[1])*($nodeB[1]-$nodeA[1]));
$this->currentDistances[$nodeA[2]][$nodeB[2]] = $dist;
if($nodeA[2]!==$nodeB[2]) {
$mean += $this->givenDistances[$nodeA[2]][$nodeB[2]];
}
}
}
// echo "<pre>";
// var_dump($this->currentDistances);
// echo "</pre>";
$check = array();
$nodesCount = count($this->nodes);
$this->mean = $mean/($nodesCount*$nodesCount);
}
public function getRSquared() {
$this->countCurrentDistances();
$sum = 0;
$SStot = 0;
$SSres = 0;
foreach($this->nodes as $nodeA) {
foreach($this->nodes as $nodeB) {
$aLab = $nodeA[2];
$bLab = $nodeB[2];
if($aLab===$bLab) {
continue;
}
$given = $this->givenDistances[$aLab][$bLab];
$computed = $this->currentDistances[$aLab][$bLab];
$SSres+=(($given-$computed)*($given-$computed));
$SStot+= ($given-$this->mean)*($given-$this->mean);
}
}
return 1 - ($SSres/$SStot);
}
protected function iterate($inverseCoefStrenth=1) {
for($i=0; $i<count($this->nodes); $i++) {
$nodeA = $this->nodes[$i];
$move = array(0,0);
$moves = 0;
for($j=0; $j<count($this->nodes); $j++) {
if($j===$i) {
continue;
}
$nodeB = $this->nodes[$j];
$dist = $this->givenDistances[$nodeA[2]][$nodeB[2]];
$AB = array($nodeB[0]-$nodeA[0], $nodeB[1]-$nodeA[1]);
$lAB = sqrt(($AB[0]*$AB[0])+($AB[1]*$AB[1]));
$coef = ($lAB - $dist)/$lAB;
$AA1 = array($AB[0]*$coef, $AB[1]*$coef);
$moves++;
$move[0]+=$AA1[0];
$move[1]+=$AA1[1];
}
if($moves>0) {
$resultingMoveX = $move[0]/($moves*$inverseCoefStrenth);
$resultingMoveY = $move[1]/($moves*$inverseCoefStrenth);
$this->nodes[$i][0]+=$resultingMoveX;
$this->nodes[$i][1]+=$resultingMoveY;
}
}
}
public function scale($iterations, $coefIncrease=0) {
$basicCoef=1;
for($i=0; $i<$iterations; $i++) {
$this->iterate($basicCoef);
//echo $this->getRSquared();
//echo " | ";
$basicCoef+=$coefIncrease;
}
}
public function coordsAsString() {
$coords = array();
foreach($this->nodes as $node) {
$coords[]="[{$node[0]}, {$node[1]}]";
}
$res = join(", ",$coords);
return "[$res]";
}
public function printCoords($pattern='[%X,%Y,"%LABEL"]') {
$coords = array();
foreach($this->nodes as $node) {
$x = $node[0];
$y = $node[1];
$label = $node[2];
$res = str_replace('%X', $x, $pattern);
$res = str_replace('%Y', $y, $res);
$res = str_replace('%LABEL', $label, $res);
$coords[]=$res;
}
$res = join(", ",$coords);
return "[$res]";
}
public function pointsCoords() {
$coords = array();
foreach($this->nodes as $node) {
$res['x'] = round($node[0]*100);
$res['y'] = round($node[1]*100);
$res['label'] = $node[2];
$coords[] = $res;
}
return $coords;
}
}

jquery tag cloud not working

Tag System I'm Using (Link)
Simply put the inline tag is never replaced by the cloud
I have my JS loading in from a folder (links confirmed)
<script type="text/javascript" src="/jquery/jqquery-1.7.2.js"></script>
<script type="text/javascript" src="/jquery/jqcloud-1.0.1.js"></script>
<link rel="stylesheet" href="/jquery/jqcloud.css" type="text/css" media="screen">
and then i use some PHP to generate the tag array
<script type="text/jscript">
var word_list = [
<?
foreach ($array as $key => $value) {
if ($value == $average) { $weight = 2;}
else if ($value > $average) { $weight = 3;}
else if ($value < $average) { $weight = 1;}
if (strlen($key) > 1 ){
echo "{text: \"".$key."\", weight:".$weight.", url: \"http://myurl.com/tags/".$key."\", title: \"".$value."\"}";
$total -= 1;
if ($total == 0) echo ",";
}
}
?>
];
$(document).ready(function() {
$("#wordcloud").jQCloud(word_list);
});
Yet all i have is an empty div in my tag section
http://jsfiddle.net/K28Mc/ Functioning example
The problem appears to be that you never close your array:
var word_list = [ // <-Note this character..
<?
foreach ($array as $key => $value) {
if ($value == $average) { $weight = 2;}
else if ($value > $average) { $weight = 3;}
else if ($value < $average) { $weight = 1;}
if (strlen($key) > 1 ){
echo "{text: \"".$key."\", weight:".$weight.", url: \"http://myurl.com/tags/".$key."\", title: \"".$value."\"}";
$total -= 1;
if ($total == 0) echo ",";
}
}
?>
}; //<------- Right here, you fail to close the array. This should be a ]. I have a feeling this is breaking everything else.
$(document).ready(function() {
$("#wordcloud").jQCloud(word_list);
});
foreach ($result['keywords'] AS $k => $keyword )
{
$font_size = rand(10, 25);
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma", "Roman", "Modern");
shuffle($fonts);
$randomFont = array_shift($fonts);
echo ' ' . '<span style="font-family:' . $randomFont . '; font-size:'.$font_size.'px;">' . $keyword['name'] . ' </span>';
}

how to create html table in php

I have the following snippet of code that basically uses explode to split out these values:
<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
$pieces = explode(";", $line);
echo $pieces[0];
echo $pieces[1];
echo $pieces[2];
echo $pieces[3];
//print_r($line);
}
?>
Data: (prod.txt)
PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2
Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.
PREFIX PART FILE
abc null /myprojects/school/out/data/feed_abc_2010120810.gz2
efg sdsu mail_efg.dat.2010120810.gz2
The Clean Way
<?php
$inputfile = file("prod.txt");
$data_lines = array();
foreach ($inputfile as $line)
{
$data_lines[] = explode(";", $line);
}
//Get column headers.
$first_line = array();
foreach ($data_lines[0] as $dl)
{
$first_line[] = explode("=", $dl);
}
$headers = array();
foreach ($first_line as $fl)
{
$headers[] = $fl[0];
}
// Get row content.
$data_cells = array();
for ($i = 0; $i < count($data_lines); $i++)
{
$data_cell = array();
for ($j = 0; $j < count($headers); $j++)
{
$data_cell[$j] = substr($data_lines[$i][$j], strpos($data_lines[$i][$j], "=")+1);
}
$data_cells[$i] = $data_cell;
unset($data_cell);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Table With PHP</title>
</head>
<body>
<table border="1">
<tr>
<?php foreach ($headers as $header): ?>
<th><?php echo $header; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach ($data_cells as $data_cell): ?>
<tr>
<?php for ($k = 0; $k < count($headers); $k++): ?>
<td><?php echo $data_cell[$k]; ?></td>
<?php endfor; ?>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
This should be flexible enough and won't require any hard-coded pair names:
<?php
$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));
foreach($lines as $i => $line) {
$pairs = explode(';', $line);
foreach($pairs as $pair) {
list($column, $value) = explode('=', $pair, 2);
$columns[$column] = true;
$rows[$i][$column] = $value;
}
}
$columns = array_keys($columns);
echo '<table><thead><tr>';
foreach($columns as $column) {
echo '<th>'.$column.'</th>';
}
echo '</tr></thead><tbody>';
foreach($rows as $row) {
echo '<tr>';
foreach($columns as $column) {
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
?>
echo '<table><tr><td>PREFIX</td><td>Part</td>File</td></tr>';
foreach ($Inputfile as $line){
$pieces = explode(";", $line);
$count=count($pieces);
echo '<tr>';
for ($counter=0; $counter <$count; $counter++)
{
echo '<td>'.$pieces[$counter].'<td>';
}
echo '</tr>';
}
Not the prettiest solution, just an example:
echo '<table><tr><td>PREFIX</td><td>PART</td><td>FILE</td></tr>';
foreach ($Inputfile as $line)
{
$pieces = explode(';', $line);
echo sprintf(
'<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
ltrim($pieces[0], 'PREFIX='),
ltrim($pieces[1], 'PART='),
ltrim($pieces[2], 'FILE=')
);
}
echo '</table>';
You've really got two problems here:
1) Parsing the information in each line into a record / associative array
2) Representing the series of these records/arrays as an HTML table.
Good code will separate these concerns somewhat.
function line2record($line) {
$recordAA = array();
$keyValuePairs = explode(';',$line);
foreach($keyValuePairs as $kvp) {
$pieces = explode('=',$kvp);
$recordAA[$pieces[0]] = $pieces[1];
}
return $recordAA;
}
function record2TR($recordAA) {
$str = implode('</td><td>',$recordAA);
return "<tr><td>$str</td></tr>";
}
After that, it's pretty much a matter of applying these two functions to each line of the file:
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line)
echo record2TR(line2record($line));
To get the header row, and the table/open close markup, you might do something like this:
function record2TH($recordAA) {
$headers = array_keys($recordAA);
$str = implode('</th><th>',$headers);
return "<tr><th>$str</th></tr>";
}
and then:
$fp = fopen('prod.txt','r');
$line = fgets($fp,MAX_LINE_LENGTH); // you'd set this constant
$firstRecord = line2record($line);
echo "<table>";
echo record2TH($firstRecord);
echo record2TR($firstRecord);
while($line = fgets($fp,MAX_LINE_LENGTH))
echo record2TR(line2record($line));
echo "</table>";
This was my approach
echo '<table id="time-table" border="2"><thead><tr >';
echo '<th style="width:40%; padding: 7px;">Course Code</th>';
echo '<th style="width:30%">Course Name</th>';
echo '<th style="width:40%">Slot</th>';
for ($x = 0; $x < 5; $x++) {
echo '<tr id=row'.$x.'>';
echo '<th style="width:40%; padding: 15px;" >',$xml_data->children()[$x]->coursecode .'</th>';
echo '<th style="width:30%">',$xml_data->children()[$x]->coursename .'</th>';
echo '<th style="width:20%">',$xml_data->children()[$x]->slot .'</th>';
}
echo '</tbody></table>';
<?php
class Table
{
private $table;
private $rows;
public function __construct()
{
}
function valueof($var, $key, $default_return_value = null, $run_value_in_this_function = '')
{
$return_value = $default_return_value;
if (is_object($var)) {
if (isset($var->$key)) {
$return_value = trim($var->$key);
}
} elseif (is_array($var)) {
if (isset($var[$key])) {
$value = $var[$key];
$return_value = is_string($value) ? trim($value) : $value;
}
} else {
$return_value = $default_return_value;
}
if (!empty($return_value) && !empty($run_value_in_this_function)) {
if (function_exists($run_value_in_this_function)) {
$return_value = $run_value_in_this_function($return_value);
}
}
return $return_value;
}
function addRow($index)
{
$this->rows[$index] = [];
$this->table['rows'][$index] = [];
}
function addRows($rows)
{
$rows = (int) $rows;
for ($r = 0; $r <= $rows; ++$r) {
$this->rows[$r] = [];
$this->table['rows'][$r] = [];
}
}
function addCell($row_index, $cell_index, $cell_value)
{
$this->table['rows'][$row_index][$cell_index] = $cell_value;
}
function updateCell($row_index, $cell_index, $cell_value)
{
$this->table['rows'][$row_index][$cell_index] = $cell_value;
}
function updateColumn($column_index, $cell_values = [])
{
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$value_index = $row_index;
$new_value = $this->valueof($cell_values, $value_index);
if (!is_null($new_value)) {
$this->updateCell($row_index, $column_index, $new_value);
}
}
}
}
}
function updateRow($row_index, $row_values = [])
{
if (isset($this->table['rows'][$row_index])) {
$columns = count($this->table['rows'][$row_index]);
foreach ($this->table['rows'][$row_index] as $column_index => $column_value) {
$value_index = $column_index-1;
$new_value = $this->valueof($row_values, $value_index);
if (!is_null($new_value)) {
$this->updateCell($row_index, $column_index, $new_value);
}
}
}
}
function addHeader($row_values = [])
{
if (!empty($row_values)) {
$this->updateRow(0, $row_values);
}
}
function addColum($column_index)
{
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$this->table['rows'][$row_index][$column_index] = null;
}
}
}
}
function addColums($columns)
{
$columns = (int) $columns;
for ($col = 1; $col <= $columns; ++$col) {
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$this->table['rows'][$row_index][$col] = null;
}
}
}
}
}
public function getTable()
{
if (isset($this->table['rows']) && is_countable($this->table['rows'])) {
$table = "<table border=\"1\" width=\"50%\">";
foreach ($this->table['rows'] as $row_index => $row_cells) {
$table .= "<tr>";
if (is_countable($row_cells)) {
foreach ($row_cells as $cell_index => $cell_value) {
if (empty($cell_value)) {
$cell_value = ' ';
}
$table .= "<td class=\"data\"> {$cell_value}</td>";
}
}
$table .= "</tr>";
}
$table .= "</table>";
}
return $table;
}
function makeTable()
{
$this->addRows(5);
$this->addColums(4);
$this->addHeader(['No', 'Name', 'Unit', 'Number']);
$this->updateColumn(1, [null, '1', '2', '3', '4', '5' ]);
$this->updateColumn(2, [null, 'Cat', 'Dog', 'Horse', 'Cow', 'Hen']);
$this->updateColumn(3, [null, 'Each', 'Each', 'Each', 'Each' ]);
$this->updateColumn(3, [null, 10,20, 5, 50, 45]);
// echo '<pre>';
// print_r($this->table);
// echo '</pre>';
$table = $this->getTable();
return $table;
}
}
$table = new Table();
print $table->makeTable();

Categories