How to display values from two separate tables from mySQL database? - php

I am trying to view values from two separate tables using a foreach loop. The user chooses a "Start semester" and an "End semester" from a drop down list, and those two semesters are stored into an array called $semesterarray
<table style='width: 75%; text-align: left;' cellpadding = '4'>
<tr bgcolor=#000090>
<th><FONT COLOR = #FFFFFF><b><?php echo $startsem ?></b></th>
<th><FONT COLOR = #FFFFFF><b><?php echo $endsem ?></b></th>
</tr>
// If $semesterarray contains 10 and 11, I want to be able to view the
// courses taken in the 10 semester and the 11 semester under two separate columns.
<?php
function getSemesterDetails($semester)
{
$output = "";
$semA = $semester."reg";
$query = "SELECT course1,course2,course3 FROM $semA";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
// row displays: [course1]=> [course2]=> [course3]=>
// Add semester code to array Keys to indicate proper semester
// [course1.11]=> [course2.11]=> [course3.11]=>
foreach ($row as $key => $value)
{
$row[$key.".".$semester] = $value;
unset($row[$key]);
}
$startcourse1 = $row['course1.'.$semester];
$startcourse2 = $row['course2.'.$semester];
$startcourse3 = $row['course3.'.$semester];
$startcoursesarray = array($startcourse1, $startcourse2, $startcourse3);
$startcourses = implode("<br>", $startcoursesarray);
$endcourse1 = $row['course1.'.$semester];
$endcourse2 = $row['course2.'.$semester];
$endcourse3 = $row['course3.'.$semester];
$endcoursesarray = array($endcourse1, $endcourse2, $endcourse3);
$endcourses = implode("<br>", $endcoursesarray);
echo "<tr bgcolor=#ABB5F6>
<td>$startcourses</td>
<td>$endcourses</td>
</tr>";
}
}
foreach ($midsemarrayA as $key => $semester)
{
echo getSemesterDetails($semA);
}
?>
Any ideas?

This should be enough for you to make a start:
function getSemesterDetails ($semester) {
$output = "";
$query = "SELECT course1,course2,course3 FROM $semester";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// row displays: [course1]=> [course2]=> [course3]=>
// Add semester code to array Keys to indicate proper semester
// [course1.11]=> [course2.11]=> [course3.11]=>
foreach ($row as $key => $value) {
$row[$key.".".$semester] = $value;
unset($row[$key]);
}
$startcourse1 = $row['course1.'.$semester];
$startcourse2 = $row['course2.'.$semester];
$startcourse3 = $row['course3.'.$semester];
$startcoursesarray = array($startcourse1, $startcourse2, $startcourse3);
$startcourses = implode("<br>", $startcoursesarray);
$endcourse1 = $row['course1.'.$semester];
$endcourse2 = $row['course2.'.$semester];
$endcourse3 = $row['course3.'.$semester];
$endcoursesarray = array($endcourse1, $endcourse2, $endcourse3);
$endcourses = implode("<br>", $endcoursesarray);
$output .= "<tr bgcolor=#ABB5F6>
<td>$startcourses</td>
<td>$endcourses</td>
</tr>";
}
return $output;
}
foreach ($semesterarray as $key => $semester) {
getSemesterDetails($semester);
}
You'll want to get it to return an array of values rather than a string, but shifting it into a subroutine should do the trick.

Related

PHP combine matching rows from associative arrays from sql and display results in html

I have 2 results set
$result_a = #pg_query($rquery_a);
$result_b = #pg_query($rquery_b);
I have 2 arrays to host and display the data on an html page:
$datas_a = array();
$datas_b = array();
$datas_a gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_occu' => $row['duree_resa']);
$i++;
}
and $datas_b gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
From these 2 existing arrays with same number of rows and same keys, I would like 3 columns, 1 column is the same for both arrays ($datas_a and $datas_b), the second column is from $datas_a and the third column is from $datas_b
It currently looks like this for $datas_a
$datas_a
It currently looks like this for $datas_b
$datas_b
It should look like this
merging columns
Now, I have used
$dataComb = array_merge($datas_a, $datas_b);
but it puts one array on top of the other while I would like to just add a column
try
$i=0;
foreach ($datas_a as $data) {
$dataComb[$i]["s1"] = $data["s1"];
$dataComb[$i]["duree_resa"] = $data["duree_resa"];
$i++;
}
$i=0;
foreach ($datas_b as $data) {
$dataComb[$i]["duree_cours"] = $data["duree_cours"];
$i++;
}
Edit - 2021-08-20
Or for something more robust given it's a basic way I only know to do this
$datas_a = array(); // associative array
$datas_b = array();
$dataComb = []; // indexed array
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_resa' => $row['duree_resa']);
$i++;
}
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
$i=0;
if($a>=$b){
foreach($datas_a as $dataa) {
$dataTmp[$i][0] = $dataa["s1"];
$dataTmp[$i][1] = $dataa["duree_resa"];
foreach($datas_b as $datab) {
if($dataa["s1"] == $datab["s1"] ){
$dataTmp[$i][2] = $datab["duree_cours"];
}
}
$i++;
}
}
elseif($a<$b){
foreach($datas_b as $datab) {
$dataTmp[$i][0] = $datab["s1"];
$dataTmp[$i][1] = $datab["duree_resa"];
foreach($datas_a as $dataa) {
if($datab["s1"] == $dataa["s1"] ){
$dataTmp[$i][2] = $dataa["duree_cours"];
}
}
$i++;
}
}
$nb_lig = $a>=$b ? $a : $b;
for ($row=0; $row<=$nb_lig; $row++) {
$dataComb[$row]["s1"] = $dataTmp[$row][0];
$dataComb[$row]["duree_resa"] = $dataTmp[$row][1];
$dataComb[$row]["duree_cours"] = $dataTmp[$row][2];
}
And there is $dataComb as an associative array that combines the data from previous arrays with matching records
foreach ($dataComb as $data){
echo '<tr>';
echo '<td>'.$data["s1"].'</td>';
echo '<td>'.$data["duree_resa"].'</td>';
echo '<td>'.$data["duree_cours"].'</td>';
echo '</tr>';
}

get user tree levels

i would like to get the levels of tree in yii2. every parent user in a tree can have an infinite number of users
->parent_user
-->sub_user [1 level]
--->sub_user [2 level]
---->etc [n level]
how i can get the level number?
My Database structure id | name | parent_id
My Tree output Code
public function getArray(){
$user = User::find()->all();
$array = [];
foreach($user as $u){
$array[$u->user_id][] = $v;
}
return $array;
}
public static function outTree($user_id){
$array = self::getArray();
if(isset($array[$user_id])){
echo '<ul>';
foreach($array[$user_id] as $v){
echo '<li>'.$v->username.'</li>';
self::outTree($v->id);
}
echo '</ul>
Any suggestions appreciated. Thanks!
<?php
function show_keys($ar, $i=1){
echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";
foreach ($ar as $k => $v ) {
echo "<td align='center' bgcolor='#EEEEEE'>
<table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>
" . $i . "
</font></td></tr></table>";
if (is_array($ar[$k])) { $i++;
show_keys ($ar[$k],$i);
}
echo "</td>";
}
echo "</tr></table>";
}
// Multidimensional array ->
$arvore = array();
$arvore['2'] = array();
$arvore['2']['22'] = array('2.1.1', '2.1.2', '2.1.3');
$arvore['2']['22'] = array('2.2.1', '2.2.2', '2.2.3');
$arvore['2']['22'] = array('2.3.1', '2.3.2', '2.3.3');
$arvore['2']['22']['222'] = array('3.1.1', '3.1.2', '3.1.3');
$arvore['2']['22']['222'] = array('3.2.1', '3.2.2', '3.2.3');
$arvore['2']['22']['222'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3');
// <-
show_keys($arvore);
?>

How can I re-organize php array of sports

I'm trying to list sport league offerings for intramurals. My current php foreach spits out all the leagues and offerings. Great.
Now I want to only show 1 instance of the sport (course), like "Basketball" and then list the multiple league offerings (offering) in columns.
I can't do another loop based on
if $nt['course'] == "Basketball" because these will change
Not sure if my mssql query needs to change or if I can use another foreach loop?
query
$sql2 = SELECT category
,course
,offering
,Semester
,spots
,registerLink from dbtable WHERE semester like "%Fall 2016%" and category like "%Leagues%" ORDER BY course
$rs= mssql_query ($sql2, $con)
or die("Error!");
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
$result[] = $row;
}
}
return $result;
exit();
my foreach loop in view:
<?php
foreach ($data as $nt) {
echo "<div class='col-md-2'>";
echo "<h2><a href='#'>".$nt['course']."</a></h2>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
So just to clarify:
category = "Leagues" which is in my query
course = Basketball and Flag Football, etc
It's very simple:-
instead of
$result[] = $row;
do
$result[ $row['course']][] = $row;
Simple solution:
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
if(!in_array($row["course"], $result))
{
array_push($result, $row["course"]);
}
array_push($result[$row["course"]], $row);
}
}
return $result;
And loop in view:
foreach($data as $key => $value)
{
echo "<h1>".$key."</h1>";
foreach($value as $nt)
{
echo "<div class='col-md-2'>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
}

json_encode returning the next rows values - PHP PDO SQL HighCharts

When trying to use json_encode from arrays in foreach() the data moves in to the next values, for example:
I have this table which is coming from the same query + php:
when using json_encode to try and fit this tables data in to highcharts, my outcome is like this:
[{"name":"User1","data":[0,2,0,0]},{"name":"User2","data":[0,2,0,0,2,0,2,4]}]
So it's moving User1's data in to User2's
My desired outcome would be:
[{"name":"User1","data":[0,2,0,0]},{"name":"User2","data":[2,0,2,4]}]
This is my code:
$uniqueHours = array();
$series = array();
$data = array();
foreach ($pdo->query("SELECT DATEPART(HOUR, AL.EndDateTime) AS 'EndHour'
FROM ActivityLog AL
WHERE
".$where."
ORDER BY AL.EndDateTime, 'EndHour' DESC") as $row)
{
if ( in_array($row['EndHour'], $uniqueHours) ) {
continue;
}
$uniqueHours[] = $row['EndHour'];
}
$ODsql = "SELECT * FROM Users";
foreach ($pdo->query($ODsql) as $row)
{
echo '<tr>';
$SCardNumber = $row['CardNumber'];
$SEmployeeName = $row['Username'];
echo '<td>'.$SEmployeeName.'</td>';
$chartValues = "";
foreach($uniqueHours as $hour)
{
$countSQL= $pdo->prepare("SELECT DISTINCT(COUNT(AL.TerminalNumber)) AS TOTALS
FROM ActivityLog AL, WavePick WP
WHERE AL.TransactionType = 'SPK' AND WP.PickedQty > 0
AND DATEPART(HOUR, AL.EndDateTime) = ".$hour."
AND AL.StartDateTime >= '".$StartDate." 00:00:00.000' AND AL.EndDateTime <= '".$StartDate." 23:59:59.000'
AND AL.OrderNumber = WP.OrderNumber
AND AL.CardNumber = '".$SCardNumber."'
");
$countSQL->execute();
$result = $countSQL->fetch(PDO::FETCH_OBJ);
$row_count = $result->TOTALS;
$totals[] = $result->TOTALS;
echo '<td>'.$row_count.'</td>';
}
echo '</tr>';
$series['name'] = $SEmployeeName;
$series['data'] = $totals;
array_push($data,$series);
}
I haven't actually put this in to the chart yet because the data is invalid.
I am using this to return the outcome:
echo "<div class='well'>";
print json_encode($results, JSON_NUMERIC_CHECK);
echo "</div>";
How can I make this data show only for each user it is linked to?
Before this loop:
foreach($uniqueHours as $hour)
empty $total array with
$total=array();
foreach($uniqueHours as $hour)

how to make implode create <br /> automatic after displaying 5 things in a row?

I want to make implode to display only 5 arrays after that it automatic creates a new row displaying 5 arrays again and it keep repeating itself. like is it possible to use <br /> or something else I had to use to do that?
$result = mysql_query("SELECT * FROM `im_album` WHERE username = '".$user_data['username']."' ");
$types = array();
$d_array = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['name'];
$d_array[] = $row['description'];
}
echo "<h1>".implode($types )."</h1>"
Try this one:
$result = mysql_query("SELECT * FROM `im_album` WHERE username = '".$user_data['username']."' ");
$types = array();
$d_array = array();
$types_str="";
$types_str_array=array();
$temp=1;
while(($row = mysql_fetch_assoc($result))) {
$types_str .=$row['name'];
if($temp!=1 && $temp%5==0)
{
$types_str_array[]=$types_str;
$types_str="";
}
$types[] = $row['name'];
$d_array[] = $row['description'];
$temp++;
}
echo "<h1>".implode("<br />",$types_str_array )."</h1>";
You could do something like this:
<?php
//sample array
$types = array("John", "Doe", "Bar", "Baz", "Stock", "Overflow", "Meta" );
//Count the number of elements in $types
$types_count = count($types);
//Use $foo1, $foo2, $foo3 as the output array names
$out_types_count = 1;
$out_types_arr = "foo".$out_types_count;
for($i=1;$i<=$types_count;$i++){
$out_types_arr[] = $types[$i];
if(($i%5) == 0){ // if we $i == 5,10,15 etc,
$out_types_count++; // use $foo2
$out_types_arr = "foo".$out_types_count;
}
}// for loop ENDS
//Echo all the output
for($i=1;$i<=$out_types_count;$i++){
for($j=0;$j<=5;$j++){
echo $out_types_arr.$i[$j];
}
echo "<br />".PHP_EOL;
}
?>
P.S. Code has some errors & minor not-desired output. Because OP has got the answer he wanted, so I am gonna correct it later, from home.

Categories