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

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];
}
}
}

Related

mysql php alphabetical listing with index-letters

I have a mysql database (plattenkiste) with bandnames
id | kuenstler
1 | Aerosmith
2 | Beck
3 | Metallica
4 | Slayer
5 | Zappa, Frank
Now i want an output in alphabetical Order with directlinks and index-letters, showing only the index-letters with bandnames.
Like
Directlinks: A|B|M|S|Z
A
Aerosmith
B
Beck
M
Metallica
S
Slayer
Z
Zappa, Frank
I have a "quick and dirty" code that does what i want:
$abc = "0123456789AÄBCDEFGHIJKLMNOÖPQRSTUÜVWXYZ";
for($i=0; $i<strlen($abc); $i++){
$char = substr($abc, $i, 1);
$query = "SELECT kuenstler FROM plattenkiste WHERE kuenstler LIKE '$char%'";
$ergebnis = $mysqli->query($query);
$num = $ergebnis->num_rows;
if ($num != 0){
echo "<a href='#$char'>$char</a> | ";
}}
for($i=0; $i<strlen($abc); $i++){
$char = substr($abc, $i, 1);
$query = "SELECT kuenstler FROM plattenkiste WHERE kuenstler LIKE '$char%'";
$ergebnis = $mysqli->query($query);
$num = $ergebnis->num_rows;
if ($num != 0){
echo "<h4 id='$char'>$char</h4>";
while($row = $ergebnis->fetch_object()){
echo $row->kuenstler . '<br />';
}
}
}
Is there a shorter, more clean way to get this done?
You can have MySQL do much of the grunt for you, by both sorting the results and (for the initial list) providing only the initial characters. Then you merely need have PHP loop over the resultsets and output the necessary HTML (for the second list, adding a header whenever it encounters a new initial character).
If your plattenkiste.kuenstler column has a case sensitive collation then you may wish to explicitly specify a case insensitive collation in the ORDER BY clauses.
$query = 'SELECT DISTINCT UCASE(LEFT(kuenstler, 1)) AS char
FROM plattenkiste
ORDER BY kuenstler';
$ergebnis = $mysqli->query($query);
if ($ergebnis) {
while ($row = $ergebnis->fetch_object()) {
$char = htmlentities($row->char);
echo "<a href='#$char'>$char</a> | ";
}
}
$query = 'SELECT kuenstler FROM plattenkiste ORDER BY kuenstler';
$ergebnis = $mysqli->query($query);
if ($ergebnis) {
$row = $ergebnis->fetch_object();
while ($row) {
$c = $row->kuenstler[0];
$char = htmlentities(strtoupper($c));
echo "<h4 id='$char'>$char</h4>";
do {
echo htmlentities($row->kuenstler), '<br />';
} while ($row = $ergebnis->fetch_object() and $row->kuenstler[0] == $c);
}
}
I've had to do things like this before as well. The easiest option is to just loop through your results and build a series of arrays...
$artists = $mysqli->query(
'SELECT kuenstler FROM Lattenkiste ORDER BY kuenstler ASC'
);
$letters = array();
// get the results and sort them into arrays
while($artist = $artists->fetch_object()) {
// ge the first letter
$firstLetter = strtoupper($artist->kuenstler{0});
// if we don't have a key for it, make it
if (!isset($letters[$firstLetter])) {
$letters[$firstLetter] = array();
}
$letters[$firstLetter] = $artist->kuenstler;
}
// output the headings
echo '<ul class="directlinks">';
foreach (array_keys($letters) as $letter) {
echo '<li>' . $letter . '</li>';
}
echo '</ul>';
// now output each set of letters
foreach (array_keys($letters) as $letter) {
echo '<h4 id="' . $letter . '">' . $letter . '</h4>';
echo '<ul class="artists">';
foreach ($letters[$letter] as $kuenstler) {
echo '<li>' . $kuenstler . '</li>';
}
echo '</ul>';
}

How to create dynamic matrix in 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";
}

How create matrix dynamic using PHP MySQL

Can any one help me? I found difficult about create matrix dynamic using PHP programming. I want value of matrix dynamic from mysql database.
Such as example :
INF 56 78 67
45 INF 78 67
45 56 INF 67
45 56 78 INF
This code it :
function random()
{
$max = 7;
if (isset($_POST['amount']))
{
$amount = (int)$_POST['amount'];
$rows = ($amount > 2 && $amount < 15) ? $amount : 3;
}
else
{
$rows = rand(3, 7);
}
for ($i = 1; $i <= $rows; $i++)
{
for ($j = 1; $j <= $rows; $j++)
{
$this->table[$i][$j] = $i == $j ? INF : rand(0, 99);
}
}
}
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;
}
Thanks

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

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.

Categories