How to create dynamic matrix in php? - php

I have this table "city" in my database:
|id |id_city_a |id_city_b|distance|
|1 |1 | 1 | 0 |
|2 |1 | 2 | 8 |
|3 |1 | 3 | 6 |
|4 |2 | 1 | 8 |
|5 |2 | 2 | 0 |
|6 |2 | 3 | 9 |
|7 |3 | 1 | 6 |
|8 |3 | 2 | 9 |
|9 |3 | 3 | 0 |
I want the end result to be in a matrix, such as:
| | 1 | 2 | 3 |
| 1 | 0 | 8 | 6 |
| 2 | 8 | 0 | 9 |
| 3 | 6 | 9 | 0 |
This is my code :
function random()
{
include('config/koneksi.php');
$result = mysql_query("select * from temp_hasil");
$n =mysql_num_rows(mysql_query("SELECT * FROM temp_hasil"));
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $n; $j++)
{
$rows = mysql_fetch_array($result);
$this->table[$i][$j] = $i == $j ? INF : $rows['id'];
}
}
}
function __toString()
{
$str = '<table class="table table-bordered" id="tableInput"> <tbody>';
$str .= '<tr><td></td>';
foreach ($this->table as $rowName => $row)
{
$str .= "<td>$rowName</td>";
}
$str .= '</tr>';
foreach ($this->table as $rowName => $row)
{
$str .= "<tr><td>$rowName</td>";
foreach ($row as $columnName => $value)
{
$str .= "<td>";
$str .=
'<input class="form-control" type="text" value="' . $value . '" name="table[' . $rowName . '][' .
$columnName . ']" requied' . ($columnName == $rowName ? ' disabled' : '') . '>';
$str .= "</td>";
}
$str .= '</tr>';
}
$str .= '</tbody></table>';
return $str;
}
}
$str .= '</tr>';
foreach ($this->table as $rowName => $row)
{
$str .= "<tr><td>$rowName</td>";
foreach ($row as $columnName => $value)
{
$str .= "<td>";
$str .=
'<input class="form-control" type="text" value="' . $value . '" name="table[' . $rowName . '][' .
$columnName . ']" requied' . ($columnName == $rowName ? ' disabled' : '') . '>';
$str .= "</td>";
}
$str .= '</tr>';
}
$str .= '</tbody></table>';
return $str;
}
`
How do I code it in php? please help me.

Make city_a index completely different from city_b index so it is easy to check.
// generate a two-dimensional matrix in here
$distMatrix = array();
foreach($tableRows as $cityDist) {
$from = $cityDist['id_city_a'];
$to = $cityDist['id_city_b'];
$dist = $cityDist['distance'];
$distMatrix[$from][$to] = $dist;
}
Display as an HTML Table...
echo '<table border="1">';
echo '<tr>';
echo '<td>', '#', '</td>';
foreach(array_keys(current($distMatrix)) as $city_b) { // city_b headings
echo '<td>', $city_b ,'</td>';
}
echo '</tr>';
foreach(array_keys($distMatrix) as $city_a) { // need the city_a as row index
echo '<tr>';
echo '<td>', $city_a, '</td>'; // city_a ad
foreach(array_keys($distMatrix[$city_a]) as $city_b) { // need the city_b as column index
echo '<td>', $distMatrix[$city_a][$city_b], '</td>'; // distance from the matrix;
}
echo '</tr>';
}
echo '</table>';
Test data - used data from #ashkufaraz
// changed the city ids so we can easily see city_a and city_b
$tableRows[0]=array("id"=>1, "id_city_a"=>1, "id_city_b"=>11, "distance"=>0);
$tableRows[1]=array("id"=>2, "id_city_a"=>1, "id_city_b"=>12, "distance"=>8);
$tableRows[2]=array("id"=>3, "id_city_a"=>1, "id_city_b"=>13, "distance"=>6);
$tableRows[3]=array("id"=>4, "id_city_a"=>2, "id_city_b"=>11, "distance"=>8);
$tableRows[4]=array("id"=>5, "id_city_a"=>2, "id_city_b"=>12, "distance"=>0);
$tableRows[5]=array("id"=>6, "id_city_a"=>2, "id_city_b"=>13, "distance"=>9);
$tableRows[6]=array("id"=>7, "id_city_a"=>3, "id_city_b"=>11, "distance"=>6);
$tableRows[7]=array("id"=>8, "id_city_a"=>3, "id_city_b"=>12, "distance"=>9);
$tableRows[8]=array("id"=>9, "id_city_a"=>3, "id_city_b"=>13, "distance"=>0);
Output:
# 11 12 13
1 0 8 6
2 8 0 9
3 6 9 0

try like this
Online Demo
$tableRows[0]=array("id"=>1,"id_city_a"=>1,"id_city_b"=>1,"distance"=>0);
$tableRows[1]=array("id"=>2,"id_city_a"=>1,"id_city_b"=>2,"distance"=>8);
$tableRows[2]=array("id"=>3,"id_city_a"=>1,"id_city_b"=>3,"distance"=>6);
$tableRows[3]=array("id"=>4,"id_city_a"=>2,"id_city_b"=>1,"distance"=>8);
$tableRows[4]=array("id"=>5,"id_city_a"=>2,"id_city_b"=>2,"distance"=>0);
$tableRows[5]=array("id"=>6,"id_city_a"=>2,"id_city_b"=>3,"distance"=>9);
$tableRows[6]=array("id"=>7,"id_city_a"=>3,"id_city_b"=>1,"distance"=>6);
$tableRows[7]=array("id"=>8,"id_city_a"=>3,"id_city_b"=>2,"distance"=>9);
$tableRows[8]=array("id"=>9,"id_city_a"=>3,"id_city_b"=>3,"distance"=>0);
$counter=0;
$result=array();
foreach($tableRows as $tableRow)
{
$result[$tableRow["id_city_a"]][$tableRow["id_city_b"]]=array("id_city_a"=>$tableRow["id_city_a"],"id_city_b"=>$tableRow["id_city_b"],"distance"=>$tableRow["distance"] );
}
now in $result[cityA][cityB]=distance
get unique_id_city_a for column
$unique_id_city_a = array_unique(array_map(function ($i) { return $i['id_city_a']; }, $tableRows));
echo "\t";
foreach($unique_id_city_a as $R)
{
echo $R."\t";
}
echo "\n";
get unique_id_city_b for rows
$unique_id_city_b = array_unique(array_map(function ($i) { return $i['id_city_b']; }, $tableRows));
foreach($result as $R1)
{
echo $unique_id_city_b[$counter++]."\t";
foreach($R1 as $R2)
{
echo $R2["distance"]."\t";
}
echo "\n";
}

Related

how to create matrix in PHP with data from mysql (2)?

I have this code:
function random()
{
include('config/koneksi.php');
$result = mysql_query("select * from temp_hasil");
$n =mysql_num_rows(mysql_query("SELECT * FROM temp_hasil"));
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $n; $j++)
{
$rows = mysql_fetch_array($result);
$this->table[$i][$j] = $i == $j ? INF : $rows['id'];
}
}
}
function __toString()
{
$str = '<table class="table table-bordered" id="tableInput"> <tbody>';
$str .= '<tr><td></td>';
foreach ($this->table as $rowName => $row)
{
$str .= "<td>$rowName</td>";
}
$str .= '</tr>';
foreach ($this->table as $rowName => $row)
{
$str .= "<tr><td>$rowName</td>";
foreach ($row as $columnName => $value)
{
$str .= "<td>";
$str .=
'<input class="form-control" type="text" value="' . $value . '" name="table[' . $rowName . '][' .
$columnName . ']" requied' . ($columnName == $rowName ? ' disabled' : '') . '>';
$str .= "</td>";
}
$str .= '</tr>';
}
$str .= '</tbody></table>';
return $str;
}
}
$str .= '</tr>';
foreach ($this->table as $rowName => $row)
{
$str .= "<tr><td>$rowName</td>";
foreach ($row as $columnName => $value)
{
$str .= "<td>";
$str .=
'<input class="form-control" type="text" value="' . $value . '" name="table[' . $rowName . '][' .
$columnName . ']" requied' . ($columnName == $rowName ? ' disabled' : '') . '>';
$str .= "</td>";
}
$str .= '</tr>';
}
$str .= '</tbody></table>';
return $str;
}`
and I have table "temp_hasil" such as:
id_temp | id |
1 | 8 |
2 | 5 |
3 | 7 |
If I run this code, it result :
1 2 3
1 | INF | 5 | 7 |
2 | | INF| |
3 | | | INF|
But I want end result such as:
1 2 3
1 | INF | 5 | 7 |
2 | 8 | INF| 7 |
3 | 8 | 5 | INF|
How do I code it in php? Is there anything wrong code? Thanks,... :)
Problem is - You can only fetch complete results once and can't get the first record in second loop. So instead, store the results in an array and use the array to create matrix.
This should work. Try this.
function random()
{
include('config/koneksi.php');
$result = mysql_query("select * from temp_hasil");
$n =mysql_num_rows(mysql_query("SELECT * FROM temp_hasil"));
$r=array();
for ($a = 1; $a <= $n; $a++)
{
$rows = mysql_fetch_array($result);
$r[]=$rows['id'];
}
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $n; $j++)
{
$this->table[$i][$j] = $i == $j ? INF : $r[$j-1];
}
}
}
Simply, you can use a while loop and store to array and then use array sizeof($r) or count($r) in for loop. Which ever you prefer.
function random()
{
include('config/koneksi.php');
$result = mysql_query("select * from temp_hasil");
$r=array();
while($rows = mysql_fetch_array($result)) {
$r[]=$rows['id'];
}
for ($i = 1; $i <= sizeof($r); $i++)
{
for ($j = 1; $j <= sizeof($r); $j++)
{
$this->table[$i][$j] = $i == $j ? INF : $r[$j-1];
}
}
}

Print new <div> on id iteration change inside php while loop from MySQL result

I have this MySQL table:
+------------+-------------+
| contact_id | _company_id |
+------------+-------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
+------------+-------------+
Im trying to print a new <div> containing all rows with the same _company_id
So far I have this code:
$previous = '';
while ($result = $stmt->fetch()) {
$current = $_company_id;
//This should be executed every first iteration and every time $_company_id changes
if ($current != $previous) { $html .= '<div id="company-' . $_company_id . '" class="tab-pane fade">'; }
//Iterate all contact_id here with the same _company_id
if ($current != $previous) { $html .= '</div>'; }
$previous = $current;
}
My desired output is:
<div id="company-1" class="tab-pane fade">123</div>
<div id="company-2" class="tab-pane fade">45</div>
Right now the output is:
<div id="company-1" class="tab-pane fade">1</div>
23
<div id="company-2" class="tab-pane fade">4</div>
5
What should I change?
$previous = null;
while ($result = $stmt->fetch()) {
$current = $_company_id;
//This should be executed every first iteration and every time $_company_id changes
if ($current !== $previous) {
if($previous !== null)
$html.='</div>';
$html .= '<div id="company-' . $_company_id . '" class="tab-pane fade">';
}
//Iterate all contact_id here with the same _company_id
$previous = $current;
}
if($previous!==null)
$html.='</div>';
Can you post your SQL query and/or some more code in this example. Off the top of my head, you could do something like:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=companies","root","root");
$sql = "select _company_id from table_name limit 0,30;";
$companies = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
foreach($companies as $company){
$contacts_sql = "select contact_id from table_name where company_id = :company_id";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":company_id", $company['_company_id'], PDO::PARAM_INT);
$stmt->execute();
$contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<div id='company-{$company['_company_id']}'>";
foreach($contacts as $contact){
echo $contact['contact_id'];
}
echo "</div>".PHP_EOL;
}
?>
Could you not?

Take HTML Output and insert it Excel Document via PHPExcel?

I already have my desired data retrieved from the database and output it via the browser for web use but now I am trying to insert it in to an excel doc and email it.
I have the beginnings of the document and am able to email it as an attachment fine, it's just how to transpose the html output into the excel document that I am stuck at as I can't think of the best way to do it.
This is how I achieve my HTML output (apologies for the length):
// print table
echo '<table>';
echo '<tr><th rowspan="2">Day</th>';
foreach($typesorder as $type) {
if(in_array($type, $types)) {
echo '<th colspan="3">' . $type . '</th>';
}
}
echo '<th colspan="3">Total Conversions</th>';
echo '</tr>';
echo '<tr>';
foreach($typesorder as $type) {
if(in_array($type, $types)) {
echo '<th>Week ' . $weekstart_A_data['week'] . ' ' . $weekstart_A_data['year'] . '</th>';
echo '<th>Week ' . $weekstart_B_data['week'] . ' ' . $weekstart_B_data['year'] . '</th>';
echo '<th>+/-</th>';
}
}
// Total Conversions section
echo '<th>Week ' . $weekstart_A_data['week'] . ' ' . $weekstart_A_data['year'] . '</th>';
echo '<th>Week ' . $weekstart_B_data['week'] . ' ' . $weekstart_B_data['year'] . '</th>';
echo '<th>+/-</th>';
echo '</tr>';
foreach($dailytotals as $thedate => $data) {
$daily_conversions = 0;
$daily_conversionsB = 0;
echo '<tr>';
echo '<td>' . date('l', strtotime($thedate)) . '</td>';
foreach($typesorder as $type) {
if(in_array($type, $types)) {
$conversions = $data[$type];
$total_conversions[$type] += $conversions;
$daily_conversions += $conversions;
$week_A_conversions = $conversions;
$week_B_conversions = $dailytotalsB[$weekstartB][$type];
$total_conversionsB[$type] += $dailytotalsB[$weekstartB][$type];
$daily_conversionsB += $week_B_conversions;
$differential = $dailytotalsB[$weekstartB][$type] - $conversions;
echo '<td>'. number_format($week_A_conversions) . '</td>';
echo '<td>'. number_format($week_B_conversions) . '</td>';
if($differential < 0 ) {
$class = "class='diffred'";
} else if($differential > 0) {
$class = "class='diffblue'";
} else {
$class='';
}
// differential between Week A and Week B
echo '<td ' . $class . '>' . $differential . '</td>';
}
}
$weekstartB = date("Y-m-d", strtotime('+1 day', strtotime($weekstartB)));
$differentialtotal = $daily_conversionsB - $daily_conversions;
echo '<td>' . number_format($daily_conversions) . '</td>';
echo '<td>' . number_format($daily_conversionsB) . '</td>';
if($differentialtotal < 0 ) {
$class = "class='diffred'";
} else if($differentialtotal > 0) {
$class = "class='diffblue'";
} else {
$class='';
}
echo '<td ' . $class . '>' . $differentialtotal . '</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td><strong>Total</strong></td>';
// reset both week A and B
$overall_conversions = 0;
$overall_conversionsB = 0;
foreach($typesorder as $type) {
if(in_array($type, $types)) {
$conversions = $total_conversions[$type];
$overall_conversions += $conversions;
$conversionsB = $total_conversionsB[$type];
$overall_conversionsB += $conversionsB;
echo '<th>' . number_format($conversions) . '</th>';
echo '<th>' . number_format($conversionsB) . '</th>';
echo '<th>' . number_format($conversionsB - $conversions) . '</th>';
}
}
echo '<th>' . number_format($overall_conversions) . '</th>';
echo '<th>' . number_format($overall_conversionsB) . '</th>';
echo '<th>' . number_format($overall_conversionsB - $overall_conversions) . '</th>';
echo '</tr>';
echo '</table>';
This outputs a table with the following structure:
----------------------------------------------------------------------------------
| | Type 1 | Type 2 | ... | Total Conversions |
| Day -------------------------------------------------------------------------|
| | Week 1 2013 | Week 1 2012 | ... | ... | ... | ... | ... |
|--------------------------------------------------------------------------------|
|Sunday | 135 | 143 | ... | ... | ... | ... | ... |
|--------------------------------------------------------------------------------|
| ... | ... | ... | ... | ... | ... | ... | ... |
|--------------------------------------------------------------------------------|
|Total | ... | ... | ... | ... | ... | ... | ... |
----------------------------------------------------------------------------------
Hopefully that makes some sense, the ... are just placeholders for repeating data.
I don't need to do any formulas since I already have all the data I need but I wouldn't rule it out as it might be easier to total using PHPExcel.
I know this is a horrible question but I am genuinely stumped how to start off. I'm not expecting the full, exact answer to my specific scenario (although that would be magical) but in reality any pointers would help.
P.S. I know how to insert data into the Excel document using PHPExcel but it's transposing my table that's the problem. I think the first step is to add all the data to a multi-dimensional array instead of printing it but I will see what the responses are first.
Also, please note that I don't want to output as CSV as I wish to automatically email the pre-prepared and formatted Excel sheet.

foreach plus for in php

I would like make:
aaa | bbb | ccc | ddd etc
1 | 1 | 1 | 1
2 | 2 | 2 | 2
3 | 3 | 3 | 3
etc
for aaa, bbb etc i use FOREACH
<table><tr>
foreach ($data as $d){
echo "<td>" . $d . "</td>";
}
</tr>
for ($i = 0; $i < 20; $i++){
echo "<tr><td>" . $i . "</td></tr>";
}
but this working not ok. how can i use loop FOR for all data from foreach?
I think you can generate your table like this:
$columns = array('aaa','bbb','ccc','ddd');
$num_cols = count($columns);
echo "<table>";
echo "<tr>";
foreach($columns as $col)
{
echo "<td>$col</td>";
}
echo "</tr>";
for($i=1;$i<20;$i++)
{
echo "<tr>";
for($j=0;$j<$num_cols;$j++)
{
echo "<td>$i</td>";
}
echo "</tr>";
}
echo "</table>";
In general depends on what $data looks like.
<?php
$data = array('aaa', 'bbb', 'ccc', 'ddd'); // Assuming that $data is a columns storage
$rows = 10; // $rows = count($data); if you wish to have same number of columns and rows
echo '<table>';
echo '<tr>';
foreach ($data AS $item)
{
echo '<td>' . $item . '</td>';
}
echo '</tr>';
for ($idx = 0; $idx < $rows; $idx++)
{
echo '<tr>';
for ($col = 1, $col_num = count($data); $col <= $col_num; $col++)
{
echo '<td>' . $idx . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
P.S. haven't tested the code.

3 time loop in present like html table?

I have an array:
$A = array(
'A'=>
array('a1'=>array(1,2,3),
'a2'=>array(1,2,3),
'a3'=>array(1,2,3)),
'B' =>
array('b1'=>array(1,2,3),
'b2'=>array(1,2,3),
'b3'=>array(1,2,3)),
'C');
How Can I use loop to present data (html table ):
-----------------------------
| | time1| time1 | time2 |
----------------------------
A | 3 | 6 | 8
-----------------------------
a1 | 1 | 2 | 2
-----------------------------
a2 | 1 | 2 | 3
-----------------------------
a3 | 1 | 2 | 3
----------------------------
B
b1
b2
b3
C
I am trying( get the total && display C instead 0):
echo '<table border="1">';
echo "<tr><td></td><td>time1</td><td>time2</td><td>time3</td></tr>";
foreach ($A as $key=>$main){
echo '<tr>';
echo "<td>$key</td>";
echo "<td>???</td>";
echo "<td>???</td>";
echo "<td>???</td>";
echo '</tr>';
foreach ($main as $k=>$sub) {
echo '<tr>';
echo "<td>$k</td>";
foreach ($sub as $kk =>$val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
}
echo '</table>';
<?php
$A = array(
'A'=>
array('a1'=>array(1,2,2),
'a2'=>array(1,2,3),
'a3'=>array(1,2,3)),
'B' =>
array('b1'=>array(1,2,3),
'b2'=>array(1,2,3),
'b3'=>array(1,2,3)),
'C'=> null); // in your case it won't be key it will be value
echo '<table border="1">';
echo "<tr><td></td><td>time1</td><td>time2</td><td>time3</td></tr>";
foreach($A as $key => $value)
{
echo "<tr><td>".$key."</td>";
if(!is_array($value))
continue;
echo "<td>".implode("</td><td>", findSum($value))."</td></tr>";
foreach($value as $cKey => $cValue){
echo "<tr><td>".$cKey."</td>";
echo "<td>".implode("</td><td>", $cValue)."</td>";
}
echo "\n";
}
function findSum($value)
{
if(!is_array($value))
return array(0);
$result = array();
foreach($value as $childValue)
{
foreach($childValue as $cKey => $cValue)
$result[$cKey] = isset($result[$cKey]) ? $result[$cKey] + $cValue : $cValue;
}
return $result;
}

Categories