Distinct single item in foreach loop - php

In my code i get a bunch of results from my database like so:
$records = $conn->prepare('SELECT sm.taak,u.username FROM schedule_mon AS sm JOIN users AS u ON sm.user_id=u.id');
$records->execute();
$results = $records -> fetchAll();
Then i loop through the results like this:
foreach( $results as $row ) {
echo $row['taak']." ".$row['username']."</br>";
}
My results look like this:
Tafel dekken Peter
Tafel afruimen Chrisformer
Afwasmachine inruimen Frek
Afwasmachine uitruimen desley
The format is basically a task and then the user that has to perform that task. I would now like to know, lets say the user that has to perform a task is named Peter. How do i give peter a different color than the others.
So if user = peter then put peter in an <li> with a certain class. So i can give it a distinct color in css.

Use a <span> around the part you want to color differently:
foreach( $results as $row ) {
if ($row['username'] == "Peter") {
echo $row['taak']." <span class='className'>".$row['username']."</span></br>";
} else {
echo $row['taak']." ".$row['username']."</br>";
}
}
Than use CSS to assign a color to the className:
.className {
color:red;
}

Related

Displaying whole table with optionally empty fields

Here is how the database looks like
So I would like to display it like
Champion name
name of the column e.g. Q name of the spell - Surging Tides
the rest of spells for that champion
Next Champion etc.,
This is the way I display Champion names right now
$champions = $conn->prepare("SELECT *
FROM champions
Where Patch_No = ?");
$champions->bind_param('s', $Patch_No);
$champions->execute();
$champions_result = $champions->get_result();
while($row = $champions_result->fetch_assoc()){
echo $row['Champion'].' '.$row['NumNotNull'].'<br>';
}
I can't really think of an easy way to do this with the least amount of queries possible.
Here is another example how it should look like
$row is an associative array, so you can loop through it with foreach and test whether the column is empty.
while($row = $champions_result->fetch_assoc()){
echo $row['Champion'].' '.$row['NumNotNull'].'<br>';
foreach ($row as $column_name => $column) {
if ($column_name == 'Champion' || $column_name == 'NumNotNull') {
continue; // These fields were already displayed above
}
if (!empty($column)) {
echo "$column_name $column<br>";
}
}
}

Display if subarrays > 3 - PHP

So I have a tv show website and I created custom lists where you can add whatever tv shows you want.
There is one table called lists (with user_id, list_title) and another table called show_lists which contains (list_id, show_id).
So my PHP is there:
<?php
$findlistsq = $conn->prepare('SELECT * FROM show_lists, shows, lists
WHERE lists.user_id = :user_id AND
lists.list_id = show_lists.list_id AND
shows.id = show_lists.show_id');
$findlistsq->execute(array(':user_id' => 2));
$listscount = $findlistsq->rowCount();
echo $listscount;
$list = array();
while ($listarray = $findlistsq->fetch()) {
$list[$listarray['list_title']][$listarray['name']] = $listarray;
}
?>
<?php
foreach ($list as $key => $show) {
echo $key; //echo title of list
foreach ($show as $key => $value) {
echo $value['name']; //echo tv shows
;
}
}
?>
Basically, I create an array to join a list to its tv shows, display the title of the list and whatever it contains and so on. My question is: I want to display the list only if there is more than 3 shows (at least 3 different $value).
Can anybody tell me how I could do that ? Thanks!!
Edit: Also, there is slight chance that I might have overcomplicated this. Let me know if I did.
Your explanation of your data is not great, but you could try doing this in the SELECT statement, this will be faster than messing with arrays.
$findlistsq = $conn->prepare('SELECT *
FROM show_lists, shows, lists
WHERE
lists.user_id = :user_id AND
lists.list_id = show_lists.list_id AND
shows.id = show_lists.show_id AND
COUNT(DISTINCT shows.id) > 3');
This will count the DISTINCT (unique) show ids and only return you a data set if there are more than 3 DISTINCT show ids.
You will want to look into is_array() and count()
$list = array('show1','show2','show3');
if(is_array($list)){
if(count($list) > 3){
//more than 3 shows found, execute code!
}
}

Grouping a SQL result set in PHP

Say I have a query the following query run:
Edit
Added order clause because the real sql statement has one.
SELECT description, amount, id FROM table ORDER BY id
In this instance, the ID is not unique to the dataset. It would return something like this.
Description Amount ID
----------- ------ --
1 Hats 45 1
2 Pants 16 1
3 Shoes 3 1
4 Dogs 5 2
5 Cats 6 2
6 Waffles 99 3
What I need to do is enclose each section of IDs in it's own div (So rows 1,2,3 in one div, 4,5 in another div and 6 in it's own div).
There are tons of solutions to this but I just can't think of one that isn't overly complicated.
I want to be able to keep the SQL how it is and somehow sort the data set in PHP so that I can loop through each section of the dataset while looping through the dataset as a whole.
Some kind of array would work but the structure of it is stumping me.
How can I get this to work? PHP solutions would be idea but theoretical will help too.
See if something like this works for you.
// execute query: Select description, amount, id from table
$results = array();
while ($row = $query_result->fetch_array()) {
if (!isset($results[$row['id']])) $results[$row['id']] = array();
$results[$row['id']][] = $row; // push $row to results for this id
}
// later on
foreach($results as $id => $data) {
// output div based on $id
foreach($data as $datum) {
// output individual data item that belongs to $id
}
}
A simple serial solution might look something like this:
$curId = ''; // track working id
$firstDiv = true; // track if inside first div
// open first div
echo '<div>';
// foreach $row
{
// when id changes, transition to new div, except when in first div
if ($row->$id != $curId) {
if ($firstDiv) {
$firstDiv = false;
} else {
// start new div
echo '</div>';
echo '<div>';
}
$curId = $row->$id; // track new current id
}
// display contents of current row
}
// close last div
echo '</div>';
Just store the id in temp variable, if the next one is different close the div and open new div
Assuming associative arrays for the db results:
$final = array();
foreach($results as $result)
{
$final[$result['id']][] = $result;
}
This leaves you with an associative array $final that groups the entries by ID

How to make a "distinct" detection on a foreach loop

At this time I have this very complex query that I loop through and I get something like this:
List of Challenges:
TEAM A
- Challenge 1
TEAM A
- Challenge 4
TEAM A
- Challege 6
And I want to change to something like:
TEAM A
- Challenge 1
- Challenge 4
- Challenge 6
My question is, since the query is a very complex one, maybe I could do this inside the loop but, if that's the case, how can we achieve something like that?
Can I ask an example case so that I can use, in order to solve this issue?
Thanks a lot,
MEM
UPDATE:
The query is something like this:
Translated:
public function listachallengesPendentes()
{
$select = $this->getAdapter()->select();
$select->from(array("e"=>"teams"),array('name'));
$select->join(array("de"=>"challengeperteam"),"e.cod_team = de.cod_teamFk",array());
$select->join(array("d"=>"challenges"),"d.cod_challenge = de.cod_challengeFk",array('title'));
$select->columns(array("e.cod_team"
,"name_team"=>"e.name"
,"d.cod_challenge"
,"name_challenge"=>"d.title"
,"d.details"
,"d.score"
,"category"=>"d.cod_categoryFk"
,"de.proof"
,"de.date_concluded"
,"de.cod_challenge_team"
));
$select->where("de.status = 0");
$select->order(array('e.cod_team DESC', 'de.cod_challenge_team DESC'));
return $this->getAdapter()->fetchAll($select);
}
So I need to add a distinct some part :s :D ?
The foreach actually is pretty basic:
foreach ($challenges as $d){
//display the name:
echo $d['name_team'];
...
}
UPDATE 2
The clean query (not tested):
SELECT e.name
,d.cod_team
,d.cod_challenge
,d.title
,d.details
,d.score
,de.proof
,de.date_concluded
,de.cod_challenge_team
FROM teams e
INNER JOIN challengeperteam de ON de.cod_teamFk = e.cod_team
INNER JOIN challenges d ON d.cod_challenge = de.cod_challengeFk
WHERE de.status = 0
ORDER BY e.cod_team DESC, de.cod_challenge_team DESC;
Something along the lines of:
$current_team = null;
foreach($challenges as $challenge){
if($current_team != $challenge->team){
$current_team = $challenge->team;
echo $current_team, "\n";
}
echo $challenge->challenge_name, "\n";
}
At a very basic level, ie in the loop, you can just detect if the TEAM A variable is equal to the current (previous) value, and if so, don't print it a second time. This relies on the result set being sorted on the TEAM A column.
However, you can also do this in the SQL query, so if you can provide the current SQL Query, I can explain how you'd update it.
you could store the array results in a multi-dimensional array like so:
$query_Challenges = "SELECT `Team`,`Challenges` FROM YourTable";
$Challenges = mysql_query($query_Challenges, $dbconnection) or die(mysql_error());
$row_Challenges = mysql_fetch_assoc($Challenges);
$challengeResults = array();
do{
if(!array_key_exists($row_Challenges['cod_team'])){
$challengeResults[$row_Challenges['cod_team']] = array();
}
$challengeResults[$row_Challenges['cod_team']][] = $row_Challenges['cod_challenge_team'];
}while($row_Challenges = mysql_fetch_assoc($Challenges));
EDIT
looking at your query statement, the data should be already sorted properly by your ORDER clause, so if you just need not repeatedly print the team as shown in codeblock 2, then something like:
$team = '';
do {
if($team != $row_Challenges['cod_team']){
echo "TEAM $row_Challenges['cod_team']<br/>";
$team = $row_Challenges['cod_team'];
}
echo " - $row_Challenges['cod_challenge_team']<br />";
}while($row_Challenges = mysql_fetch_assoc($Challenges));
you could easily substitute a foreach for the do loop, as long as there is a variable used as the "current team" and an if statement used to say "dont print the next team name unless its different than the current team name"

Sorting and Grouping mySQL Results in html

I have a mysql table with 3 fields: id, client, group and some data.
I need to display the results in groups, on a css table, like this:
group A
- John
- Paul
- Ringo
- George
group B
- Mick
- Keith
- Charlie
group C
- Axl
- Slash
- Izzy
I have to put a while inside another while? I really don't get the logic behing this conditional... Can someone help me?
I have this so far:
while($row = mysql_fetch_array($result) ){
echo "<div>".$row['group']."</div>";
while($currentGroup != $group ){
echo "<div><B>".$row['id']."</b></div>";
echo "<div>".$row['client']."</div>";
}
$currentGroup = $group;
}
Thanks!
Like this:
$currentGroup = false;
while ($row = mysql_fetch_array($result))
{
if ($row['group'] !== $currentGroup)
{
echo "<div>".$row['group']."</div>";
$currentGroup = $row['group'];
}
echo "<div><B>".$row['id']."</b></div>";
echo "<div>".$row['client']."</div>";
}

Categories