Bear with me here--this may be a bit confusing.
I am retrieving two sets of data with SQL. Here's the code, with the query. I'm using Zend Framework.
$assignments = $db->fetchAll("SELECT id,name,class FROM assignments");
foreach($assignments as $a) {
$assignmentID = $a['id'];
$studentData = $db->fetchAll(
"SELECT student,assignment,status,assignmentID FROM student_assignments WHERE assignmentID='$assignmentID'"
);
echo "<th>".$a['name']."</th>";
foreach($studentData as $s) {
$bottom .= "<tr><td>" . $s['student'] . " " . $s['assignmentID']
. " ".$s['status'] . "</td></tr>";
$i++;
}
}
echo "</tr>$bottom;";
Here's what the output looks like in the HTML:
|Assignment on 07/07/2012| |Assignment on 07/12/2012| |Assignment on 07/15/2012|
117 1 Y
332 1 N
36 1 N
420 1 N
332 1 Y
326 2 N
212 2 N
461 2 N
117 2 N
212 2 N
212 3 N
326 3 N
117 3 Y
420 3 Y
Now the top part is working great -- it's dynamically showing each assignment in the database. But I've been trying to figure out a way to get the appropriate data to show under those columns, to no effect. This is the closest I've gotten to making it look somewhat correct.
Essentially, the data that has "2" and "3" in the middle should go into the 2nd and 3rd columns, respectively. But this isn't happening because all the data is stored into the $bottom variable, rather than the data for each assignment.
Does anyone have any suggestions? This is driving me crazy, and I feel like the solution is staring me in the face.
Thanks!
First you want to iterate through every of your student assignments, and left join the assignments table to it so you can know the name of the assignment that it is related to.
$students = $db->fetchAll('SELECT sa.student,sa.assignment,sa.status,sa.assignmentID,a.name
FROM student_assignments AS sa
LEFT JOIN assignments AS a ON sa.assignmentID=a.id');
Then with the results, you can build an array to regroup everyone with the same assignment:
$columns = Array();
foreach($students as $s) {
$row = '<tr><td>'.$s['student'].' '.$s['assignmentID'].' '.$s['status'].'</td></tr>';
array_push($columns[$s['name']], $row);
}
Then with this array, you can finally print your content:
foreach ($columns as $key=>$value) {
echo '<th>'.$key.'</th>';
foreach ($value as $v) {
echo $v;
}
}
Of course this can be more compact (reduced into nested loops), and I have no way to fully test it, but it should help you in your process ;)
Related
I am just coding in PHP but not understand below-mentioned coding so please help for understanding coding simply
$new_array=array(100,101,61,1075);
foreach($new_array as $value){
if(!($value%2)){
continue;
}
}
You may read this condition as "is number $value can be divided by 2 without a remainder?"
foreach
this is a Array method which we can use to execute on each element of the array. So in your code
foreach($new_array as $value){
This will assign
$value[0] = 100
$value[1] = 101
$value[2] = 61
$value[3] = 1075
Then in php % mean modules. When this operator is used within two numbers it will output the remainder after deviding first number from second number.See below examples.
5%5 = 0
5%4 = 1
5%3 = 2
10%7 = 3
($value%2)
In here each assigned values from array will be divided from 2 and check the remainder.
$value[0] = 100 => 100%2 = 0
$value[1] = 101 => 101%2 = 1
$value[2] = 61 => 61%2 = 1
$value[3] = 1075 => 1075%2 = 1
(!($value%2)) After using NOT operator(!). This means that ($value%2) should be false.It means that ($value%2) should output a value equal to 0. You can check and understand this code as below.
<?php
$new_array=array(100,101,61,1075);
foreach($new_array as $value){
if(!($value%2)){
echo($value." " );
}
}
?>
Output =100
?php
$new_array=array(100,101,61,1075);
foreach($new_array as $value){
if(($value%2)){
echo($value." , " );
}
}
?>
Output = 101 , 61 , 1075 ,
So hope you can have a idea with this.
For more just follow this links.click here to know about modules operator via official document
Thanks
I am adding in feed Ads to my website. I have a foreach statement that creates a list of posts. I have created a counter that is supposed to count every four posts and insert the Ad content then repeat.
I have tried some other iterations of this but this is the one I can actually get to do something. I can find a lot of info on this exact thing pertaining to wordpress. But I am running cake php and would prefer a pure php solution.
<?php
$count = 1;
foreach($stories as $story) {
echo '<h2>'.$story->title.'</h2>';
if(!empty($story->excerpt)) {
echo $story->excerpt;
} else {
echo limit_text($story->body);
}
if ($count % 4 == 1) {
echo AD_SENSE_INFEED;
}
}
$count++;
?>
This code is what I currently have but its not working the way I would like it to. As if now it basically goes every other. So POST, AD, POST AD...etc.
Your problem isn't a coding problem, its a math problem. What you're using is called modulos or remainders basically.
So that said:
if ($count % 4 == 1) {
For it to equal 1 we have to feed in something that goes in evenly once and leaves one more.
What you want to do is:
if ($count % 4 == 0) {
Aka it means there's no remainder, 4 goes into it evenly with nothing left over.
As #RiggsFolly mentioned and I completely missed this(Give his comment a up vote) your $count variable should be incremented inside the loop as well otherwise it will only increment once after the loop ends.
You can get rid of count all together (and just use the numeric index of the array)
//just some "test" data
$stories = array_fill(0, 100, []);
foreach( $stories as $count => $story) {
echo $count." ".($count % 4)."\n";
if ($count % 4 == 3) {
echo "--------------------------------------\n";
}
}
Output:
0 0
1 1
2 2
3 3
--------------------------------------
4 0
5 1
6 2
7 3
--------------------------------------
...
Sandbox
If your not sure if the keys are in proper order, you can reset them:
foreach(array_values($stories) as $count => $story) {
Obviously an array starts at 0, so you have to offset the % result a bit ... lol ... Yes I am to lazy to increment.
I’m currently working on a web site database. The entire site is coded in PHP (procedural style and not object oriented), of course with the obligatory CSS/HTML, etc.
I have everything working properly, but I am having trouble figuring out how to format search results the way I’d like.
Right now, I am displaying my search results in table format, with each cell of the table displaying a different variable from the search. All these little tables display vertically in one column, one after the other, until the end of the results.
What I am trying to do is display two columns of search results, side by side, to fit more results on the screen at one time. I have been able to display two columns of duplicate results, but I’d like two columns of alternating, non-duplicate results.
The current layout of my results is something like:
Result 1
Result 2
Result 3
Result 4
What I have been able to accomplish in my attempts:
Result 1 Result 1
Result 2 Result 2
Result 3 Result 3
Result 4 Result 4
What I would like to have:
Result 1 Result 2
Result 3 Result 4
Result 5 Result 6
Result 7 Result 8
Can anyone shed some light on how to achieve this? I’m not sure if it's a simple CSS/HTML formatting solution, or a PHP/MySQL solution.
Below is the code that specifically relates to the loop that displays my results:
$link = mysqli_connect( ALL MY INFO );
include('strings.php'); //This script sets the SQL search string based on user input.
echo '<br />';
$query = mysqli_query($link, $string) or die ("Error retrieving search results. Error in (main.php) search function.");
$resultrows = mysqli_num_rows($query);
echo '<table>
<tr>
<td colspan=2>
<h3>Showing '.$resultrows.' results. </h3>
</td>
</tr>
<tr>
<td>';
while ($result = mysqli_fetch_assoc($query)){
include('results.php'); //This script formats each search result
}
echo ' </td>
<td>';
$query = mysqli_query($link, $string) or die ("Error retrieving search results. Error in (main.php) search function.");
while ($result = mysqli_fetch_assoc($query)){
include('results.php');
}
echo ' </td>
</tr>
</table>';
I believe the magical solution to your problem would be to use the modulus (remainder) operator in PHP:
Remainder of $a divided by $b.
Might be an odd concept to understand if you’re not into math—and programming is all about logic really—but once you get what a modulus (remainder) operator can do, it is a magical thing.
Basically calculate a modulus based on a counter within a loop. And then at that point the remainder of the modulus value would be 0… Et voilà! You can do something! The examples below use tables and rows, but the same, basic concept could be used for other HTML elements or any formatting logic.
For example, let’s take this simple PHP code to create a table based on a simple alphabet array:
$array = range('a','z');
echo '<table border="1">';
echo '<tr>';
foreach ($array as $key => $value) {
echo '<td>';
echo $value;
echo '</td>';
}
echo '</tr>';
echo '</table>';
The output would be one table with one large ugly row that renders like this:
a b c d e f g h i j k l m n o p q r s t u v w x y z
But if we add some modulus logic to the mix like this:
$row_cell_amount = 2;
$array = range('a','z');
echo '<table border="1">';
echo '<tr>';
$counter = 1;
foreach ($array as $key => $value) {
echo '<td>';
echo $value;
echo '</td>';
if ($counter % $row_cell_amount == 0 && $counter != 0) {
echo '</tr>';
echo '<tr>';
}
$counter++;
}
echo '</tr>';
echo '</table>';
The output will cleanly add a new row every time the $counter value evenly matches the modulus operator resulting in 0; aka: no remainder. So the output would look like this with a value of 2 for the $row_cell_amount:
a b
c d
e f
g h
i j
k l
m n
o p
q r
s t
u v
w x
y z
And if you adjusted the $row_cell_amount to be something like 4, the output would be something like this:
a b c d
e f g h
i j k l
m n o p
q r s t
u v w x
y z
Small note but in this simple example you can perhaps set $key+1 instead of creating a $counter but just showing the $counter method since you might be dealing with associative arrays that are non-numerical or non-numerically ordered as far as key values go.
I have a database which has 6 column A B C D E X, for each combination of ABCDE I have a different value of X.
I need a way to search through, that will allow all values of X for different combinations (for example all X when A=1, or all X when A=1 and B=2 etc)
My thought was to translate it into a 5-D array which looks like this:
Array[A][B][C][D][E]=X;
But now I'm trying to extract sub arrays, when I don't know how may of the dimensions will be constant. So I need to be able to extract all value of X for Array[1][5][][][] or Array[2][4][5][][]… etc.
And I'm totally stuck.
I'm trying to do 6 loops one inside another but I don't know how to handle those that are constant.
Help with ideas will be very very helpful.
Edit
Database:
A B C D E X
1 1 1 1 1 53
1 1 2 3 2 34
2 1 1 4 2 64
Turned it into an array:
Array[1][1][1][1][1]=53
Array[1][1][2][3][2]=34
For
Input: A=1
Output 53,34
Input A=1,B=1,C=1
Output: 53,
etc
Try this then
<?php
$arr = array();
$result = mysql_query("SELECT A,B,C,D,E,X FROM table_name ORDER BY A ASC,B ASC,C ASC,D ASC,E ASC");
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
array_push($arr,$row);
}
}
function search($arr,$values) {
$return = array();
foreach($arr AS $key => $value) {
$ok = true;
foreach(array('A','B','C','D','E') AS $letter) {
if(array_key_exists($letter,$values)) {
if($value[$letter] != $values[$letter]) {
$ok = false;
break;
}
}
}
if($ok) array_push($return,$value['X']);
}
return (($return) ? implode(',',$return) : false);
}
echo '<pre>';
print_r(search($arr,array('A' => 1)));
echo '</pre>';
?>
I have come to this part of script so far:
dif($result>0)
{
$ii=0;
$jj=0;
while (odbc_fetch_row($result))
{
for ($jj = 1; $jj <= odbc_num_fields($result); $jj++)
{
$rr[$ii][$jj]=odbc_result($result,$jj);
if(is_null($rr[$ii][$jj]))
$rr[$ii][$jj] = noData;
echo $rr[$ii][$jj];
echo "<br />";
}
$ii++;
}
}
This works good for creating and populating dynamic tables. But i need also to create dynamic number of single line arrays which consist of column values of arrays i get previously.
Example:
if i get
Array1
2012.01.01 10 20 30
2012.01.02 1 2 3
2012.01.03 11 22 33
i need to convert to
Array2
2012.01.01 2012.01.02 2012.01.03
Array3
10 1 11
Array4
20 2 22
Array5
30 3 33
As i mentioned before the first part of script is needed, so is there a possibility to use result to create single line arrays for further use? I suppose i'm missing something...
What is wrong with a for loop and adding the elements to an array?'
$rr = array(array(1,2,3,4,5),array(6,7,8,9,0),array(11,22,33,44,55));
$result = array();
for($j=0;$j<count($rr[0]);$j++){
$col = array();
for($i=0;$i<count($rr);$i++) {
array_push($col,$rr[$i][$j]);
}
array_push($result,$col);
}
print_r($result);
for a demo see this codepad: http://codepad.org/wgSCtoMV