I would like to take the result from an SQL that looks like this
id name kg date
1 ABC 3 2017-09-14
1 ABC 2 2017-09-15
2 DEF 2 2017-09-14
2 DEF 5 2017-09-15
2 DEF 5 2017-09-16
2 DEF 3 2017-09-17
3 GHI 3 2017-09-15
3 GHI 6 2017-09-17
And put it into an array (or something else that I can loop through) so it looks like this
id name 2017-09-10 2017-09-11 2017-09-12 2017-09-13 2017-09-14 2017-09-15 2017-09-16 2017-09-17
1 ABC 3 kg 2 kg
2 DEF 2 kg 5 kg 5 kg 3 kg
3 GHI 3 kg 6 kg
It will only hold dates from last sunday until this sunday (Active week).
I haven't worked with arrays before, but of what I have read so far I think I have to create an array inside another array to achive this? I am thinking that from the SQL result I will go through each row and push the values into right row depending if the id already exists. One id could only have unique dates.
while ($row = odbc_fetch_row($resultSQL)){
Create an array with the columns above and push the result from the SQl
into the array on a new row or an existing column if the ID is
already in the array.
}
Anyone have any ideas how to achieve this? Thanks.
EDIT:
Solution: I have now done like this which achives the result I wanted.
//create two arrays
$items=array();
$dates=array();
//loop through the SQL result and put it into the arrays
while ($row = odbc_fetch_row($resultSQL)){
$ITEMNO=odbc_result($resultSQL,"id");
$ITEMNAME=odbc_result($resultSQL,"name");
$RecQtyDay=odbc_result($resultSQL,"kg");
$items[$ITEMNO] = $ITEMNAME;
$dates[$REGDATE][$ITEMNO] = $RecQtyDay;
}
//sort the dates array
ksort($dates);
//loop through and print out dates array within the item array
foreach ($items as $ITEMNO => $ITEMNAME) {
echo "$ITEMNO $ITEMNAME ";
foreach ($dates as $REGDATE => $values) {
if (isset($values[$ITEMNO])) echo "$REGDATE $values[$ITEMNO]";
}
echo"<BR>";
}
As you fetch your query results, build two arrays, one with all the items, and another that's grouped by date with values for any items that have records for each date.
while ($row = odbc_fetch_row($resultSQL)) {
$items[$row['id']] = $row['name'];
$dates[$row['date']][$row['id']] = $row['kg'];
}
Sort the dates/values array by key (date)
ksort($dates);
Then loop over your array of items to generate the rows. Within each row, loop over the array of dates and output the value for that id and date.
foreach ($items as $id => $name) {
echo "$id $name";
foreach ($dates as $date => $values) {
if (isset($values[$id])) echo "$value kg";
}
}
This output won't be neatly formatted, but I don't know exactly how you're planning to output this, so I'll leave that up to you.
Related
I want to get my output like this
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
I am trying like this:
<?php
for($a=1; $a<=16; $a++)
{
for($b=$a; $b>=1; $b--)
{
echo "$b";
}
echo "<br>";
}
?>
The above code gives me the wrong output.
Let's debug.
You are starting from 1 in your outer loop and in your inner loop, you are going from $a till 1 times.
This doesn't comply with your requirements because we have to print an increasing sequence in each row.
You can also notice that every number in a row differs by 4.
So, logic would be like below:
Pseudocode:
rows = 4
starting_number = 1
loop from 1 to rows
number = starting_number
loop from 1 to 4 // since each row has 4 numbers
print number
number += 4
print new_line
starting_number++
Demo: https://3v4l.org/9YjIP
I wanted to know if there is any way where i can calculate time difference between two rows. I want to calculate time difference for name -> test etc. The name can be in any order.
I want to know if test has two times at row 1 and 3 and then at row 7 and 11, can i calculate time difference between these rows? i.e for row 1 and 3, and other for row 7 and 11.
below image with my database
try using TIMEDIFF() and subquery
SELECT TIMEDIFF((SELECT `entered_at` FROM `demo_test3` WHERE `id`='1'),
(SELECT `entered_at` FROM `demo_test3` WHERE `id`='3'))
If you want to check the difference in PHP you can do something like this.
function secondsBetweenRows($first, $second)
{
return strtotime($second->entered_at) - strtotime($first->entered_at);
}
// group rows by users
$users = []
foreach ($rows as $row) {
$users[$row->name] = $row;
}
// check row difference
$timeDiff = [];
foreach ($users as $userName => $userRows) {
// assume there are always to, if not do some checks here
$timeDiff[$userName] = secondsBetweenRows($userRows[1], $userRows[0]);
}
print_r($timeDiff);
/*
Array
(
[test] => 24
[test1] => 26
)
*/
I am building a leaderboard (scorebored) for a poker tournament. My aim is to echo data to a table to display scores for the season and scores all time. I want the table to run in order with the highest season points at the top.
I am getting an error message that reads:
Notice: Undefined index: season in C:\wamp\www\UPT Site\leaders.php on line 11
When I print_r an array from the $allplayers array, it shows that all the players arrays are going in correctly, including the [season] key and value declared on line 6 in the bit below...
Can anyone please tell me how to fix my code? (note, the real code doesn't have line numbers in it, I just added them here to make discussion easier).
1 foreach($allplayers as $player){
2 $i = $player[1];
3 if (${"seasonplayerid" . $i}){
4 $sum = array_sum(${"seasonplayerid" . $i});}
5 //$sum = points this season.
6 ${"playerid" . $i}['season'] = $sum;
7 }
8 function val_sort($array,$key) {
9 //Loop through and get the values of our specified key
10 foreach($array as $k=>$v) {
11 $b[] = strtolower($v[$key]);
12 }
13 asort($b);
14 /* foreach($b as $k=>$v) {
15 $c[] = $array[$k];
16 }return $c;
17 */
18 }
19 $sorted = val_sort($allplayers, '[season]');
20 foreach($allplayers as $player){
21 $i = $player[1];
22 echo ("<tr><td>" . $player[0] . $t . ${"playerid" . $i}[3] . $t . ${"playerid" . $i}[4] . $t. ${"playerid" . $i}['season'] . $t. count(${"seasonplayerid" . $i}). "</td><tr>");
23 }
Here is the print_r output for array $playerid1:
Array ( [0] => Jonathan Thompson [1] => 1 [2] => 2015-S 3 [3] => 944 [4] => 7 [season] => 470 )
Here is a key of the information in the array:
/*
$allplayers is a multidimentional array, containing many arrays of players called $playerid1, $playerid2, $playerid3 etc
playerid1[0] = Player name
playerid1[1] = Player ID
playerid1[2] = Current season
playerid1[3] = total points earned
playerid1[4] = total games played games
playerid1[season] = points earned in current season
*/
Looks like at line 19 you are trying to pass key in second parameter but defined it incorrectly.So, to call function val_sort($array,$key) you have to do something like that.
Therefore at line 19 change
$sorted = val_sort($allplayers, '[season]');
to
$sorted = val_sort($allplayers, 'season');
Also i suggest you to use data table it is good and fast
Instead of below line
$sorted = val_sort($allplayers, '[season]');
you should pass the key as below
$sorted = val_sort($allplayers, 'season');
Hope this helps.
I did a dodgy quick fix in this instance.
I wrote a loop to array_pop each array inside the main array, and created a new variable for each piece of data as the array_pop loop was going.
I also array_pushed the data I wanted to sort by and an ID number to a new array.
I used rsort to sort the new array, then looped through it using the ID number to reconstruct a 3rd array in the order I wanted to output data.
Next time I will take the advice of #rocky and do a data table. I may even go back to redo this page as a data table. To be honest, I'd never heard of a data table before yesterday. Once I've given this project over to the boss I'll be investing my time in learning about data tables and AJAX.
Thank you all for your tips, but the quick fix will have to do this time as I am time poor (This site needs to be live tomorrow morning).
As the title what I'm trying to do is get numbers from database which I already do display them from descending order which I do. Patch numbers are in format X.XX so 2.01 2.05 2.22 and so on I want to label numbers between 2.00 - 2.highest one as Season 2 so Season 2 then patches like 2.99 2.85 2.04 2.00 etc.
My PHP:
foreach($patches as $patch)
{
if(substr($patch, -2)=="00"){
echo 'Season '.substr($patch, 0,1).'<br>';}
echo ''.$patch.'<br/>';
}
And my query:
$patches = $conn->prepare("SELECT Patch_No FROM info ORDER BY Patch_No DESC");
$patches->execute();
$patchesresult = $patches->get_result();
while($data1 = $patchesresult->fetch_assoc()){
$patch[$i]=$data1["Patch_No"];
$i+=1;
}
I probably have to check what is currently the highest patch so It could write first title Season XX
UPDATE - my 2D array:
$i=$j=0;
foreach($patches as $patch)
{
if($j!=0){
if(substr($patch, 0,1)!=substr($patch_array[$i][$j-1],0,1)){
$i+=1;
$j=0;
}
}
echo '$patch_array['.$i.']['.$j.'] '.$patch_array[$i][$j]=$patch.' substr$patch='.substr($patch, 0,1).' substr_previous: '.substr($patch_array[$i][$j-1],0,1).'<br/>';
$j+=1;
}
The array saves under [$i][$j] $i - is for patches with the same first number so 2.xx 2.xx 2.xx will be under the same $i and $j are for endings .01 .03 .04
so
[0][1] [0][2] [0][3] - {2.50 2.14 2.01}
[1][1] [1][2] [1][3] - {3.03 3.10 3.02}
Now I need to figure out displaying bit second loop
I changed up some syntax and variable names to make it a bit less confusing, but I think this is what you are going for. Also changed (improved) your query syntax.
$patches = $conn->prepare("SELECT Patch_No FROM info ORDER BY Patch_No DESC");
$patches->execute();
$patches->bind_result($patchNum);
$episodes=array();
while($patches->fetch_assoc()){
//build 1d array
$data=array($patchNum, substr($patch,0,1));
//push 1d array to array of arrays (2d array)
$episodes[]=$data;
echo '<a href="../index.php?Patch_No='.$patchNum.'"
class="patches"
>'.$patch.'</a><br/>';
}
Let's assume I have a table similar to this:
Id Name Value1 Value2 Value3
1 Bla 1 5 1
2 Blu 4 0 2
How to I put this into a matrix format (or similar) in PHP so I can work with it?
I wanted to do some calculations and sorting with the part that contains:
1 5 1
4 0 2
So I could then order and permantely change the main matrix. For example:
Assign a weight of 50% (or other) to each column and then move the columns associated with the lower values to the left.
Example:
1*0.5 + 4*0.5 = 2.5
5*0.5 + 0*0.5 = 2.5
1*0.5 + 2*0.5 = 1.5
Final output:
Id Name Value3 Value2 Value1
1 Bla 1 5 1
2 Blu 2 0 4
In C this was very easy to do but in PHP seems to me it's very complicated to do this because there isn't an object like M[i,j].
You need to access the column in each iteration of your query, you can't access it directly like you can with a row result:
$values = array();
$multiplier = 0.5;
foreach($result as $row) {
$values[1] += $row['value1'] * $multiplier;
$values[2] += $row['value2'] * $multiplier;
$values[3] += $row['value3'] * $multiplier;
}
print_r($values);
Depending on the names of your columns though, you could loop through them in PHP to define variables or array keys instead of doing it by hand (especially if you have lots of them). Depends on your column names. If you have lots that aren't related by numbers etc, you could loop through the column names and exclude certain ones e.g. id, name etc from your processing. In that case, you'd leave the first line above, insert a variable in place of 1 and value1, and check to make sure the array key exists before using the += operator as it will often throw an error if it's not already defined:
if(!array_key_exists($yourfield, $values))
$values[$yourfield] = 0;
// continue...