How do I insert values into an multidimensional-array, then show them? - php

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!

Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.

$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);

<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

Related

Order after executed?

Im trying to do a PHP script where it order users based on a point system. Problem is that the points is calculated after I execute the users. Like this:
$getScore = $db->prepare("SELECT * FROM `users`");
$getScore->execute();
$results = $getScore->fetchAll();
foreach($results as $row):
$likes = $get->likes("user", $row["id"]);
$subscribers = $get->subscribers("user", $row["id"]);
$score = $get->score($likes, $subscribers, $row["date"]);
echo $row["username"];
endforeach;
Without having another execution how do I order the results? I want the user with highest value on $score to be shown first. I've tried alot of things but without succession.
Thanks in advance!
You can implement this different ways.
If you have already loaded all the data from the databse you can order them using PHP.
Custom sorting can be done using usort.
PHP.net - usort documentation
Maybe you could use something like this:
$users = array();
// Load all the users and calculate scores
foreach($results as $row):
$users[$row["username"]] = $get->score($likes, $subscribers, $row["date"]);
endforeach;
// Sort users based on score
sort($users);
// Output users, sorted by score
foreach($score as $key => $row):
echo $key, " score:", $score;
endforeach;
If you would like to use a more complex data structure, all you have to do is implement the special comparision to ensure ordering by score with usort.
If you store the points in the database, then you could use a special query including an ORDER BY clause, this way returning the users already ordered.
I think using the DBMS to order the users would result in a more scalable solution. If you have really high number of users, it is not going to perform well to sort all the users each page load.
First, sorry for suggesting another execution flow. Next, this is my solution:
$getScore = $db->prepare("SELECT * FROM `users`;");
$getScore->execute();
$results = $getScore->fetchAll();
// Result is something like [rownum][colomname]
array_walk_recursive($results, function($item, $key) {
$id = $item["id"];
$date = $item["date"];
$arr = array();
$arr['likes'] = $get->likes("user", $id);
$arr['subscribers'] = $get->subscribers("user", $id);
$arr["score"] = $get->score($arr["likes"],
$arr["subscribers"],
$date);
$item = array_merge($item, $arr);
});
In this code you get the results from your database. Next you calculate things like the score and you add this to the array.
To sort this array on the score you can use the PHP multisort function (http://php.net/manual/en/function.array-multisort.php):
foreach ($results as $key => $row) {
$score[$key] = $row["score"];
}
array_multisort($score, SORT_DESC, $results);
When you're looping your loop to print the data for example you can do this:
foreach($results as $row) {
$likes = $row["likes"];
$subscribers = $row["subscribers"];
$score = $row["score"];
echo("your stuff over here");
}
Good luck!

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

PHP assign result from nested query into array

I need help in order to assign the results of a nested query into array. This is the scenario:
$Date_Collection = mysql_query("SELECT DISTINCT Date FROM TblDate");
while($date = mysql_fetch_array($Date_Collection)) // Loop through all the dates
{
$var_date = $date['Date'];
$result = mysql_query("select min(Speed) as Min_spd, max (Speed) as Max_spd, avg
(Speed) as Avg_spd from ... where Date= $var_date");
while($row = mysql_fetch_array($result))
{
echo "row[Min_spd]";
echo "row[Max_spd]";
echo "row[Avg_spd]";
}
}
The output from this query is like this:
Min_Spd |Max_Spd |Avg_Spd| Date|
12.0| 25.0| 20.4| 2012-10-01|
11.0| 28.0| 21.4| 2012-10-02|
10.0| 26.0| 23.4| 2012-10-05|
08.0| 22.0| 21.4| 2012-10-08|
I basically need to show the sum of Min_Spd, Sum of Max_spd, Sum of Avg_spd for all these dates. So, I thought that If I can assign these values into an array and later compute these sum from the array, it might be a good idea.
Can anyone please help me regarding this? Can I use an array to store the values and later access these values and calculate the sum of these values. If I can use an array, could anyone please show me the syntax of using array in PHP. I would really appreciate any help regarding this.
Is there any alternative way rather than using an array, such as creating a temporary table to save these values and later delete the temporary table. If a temporary table can be used, could you please show me how to do that. I could use the temptable for a single loop, but there is a nested loop and I don't exactly know what to do to create a temp table inside the nested loop to store all the values.
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
then later on you can do
foreach($data as $row) {
echo $row['Min_spd'];
echo ...
...
}
I don't know if the MySQL SUM function can be used to do that on te query, try it. But on this example, using arrays you should store the values and then use array_sum to return the sum of the elements. Something like this:
$min_spd = array();
$max_spd = array();
$avg_spd = array();
while($row = mysql_fetch_assoc($result))
{
$min_spd[] = $row['Min_spd'];
$max_spd[] = $row['Max_spd'];
$avg_spd[] = $row['Avg_spd'];
}
echo array_sum($min_spd);
It can also be done using variables to store and add the values:
$min_spd = 0;
$max_spd = 0;
$avg_spd = 0;
while($row = mysql_fetch_assoc($result))
{
$min_spd += $row['Min_spd'];
$max_spd += $row['Max_spd'];
$avg_spd += $row['Avg_spd'];
}
echo $min_spd;
I would first of all save yourself a nested query by doing the first query as:
$result = mysql_query("select Date, min(Speed) as Min_spd, max (Speed) as Max_spd, avg(Speed) as Avg_spd from ... group by Date")
And then create a running total for the sums as you're looping through each row:
$sumMinSpeeds=0;
$sumMaxSpeeds=0;
$sumAvgSpeeds=0;
while($row = mysql_fetch_array($result))
{
echo row['Min_spd'];
echo row['Max_spd'];
echo row['Avg_spd'];
$sumMinSpeeds += $row['Min_spd'];
$sumMinSpeeds += $row['Max_spd'];
$sumMinSpeeds += $row['Avg_spd'];
}
echo $sumMinSpeeds;
echo $sumMaxSpeeds;
echo $sumAvgSpeeds;
Instead of doing several MySQL queries in a loop, consider constructing such a query, which will return all the results you need.
SQL
First of all, it would make sense to use the GROUP SQL construct.
SELECT
s.Date date,
MIN(s.Speed) min,
MAX(s.Speed) max,
AVG(s.Speed) avg
FROM speed_table s
WHERE s.Date IN (SELECT DISTINCT d.Date FROM date_table d)
GROUP BY s.Date
It is important to understand what each part of this query does. If you run into any problems, consult the MySQL reference manual.
PHP
Forget about using mysql_* functions: they are deprecated and better implementations have emerged: PDO and mysqli. My example uses PDO.
try {
$dbh = new \PDO('mysql:dbname=my_db_name;host=127.0.0.1', 'dbuser', 'dbpass');
} catch (\PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = '...'; // This is the query
$stmt = $pdo->prepare($sql);
$stmt->execute();
You can now either iterate over the returned result set
while ($row = $stmt->fetch()) {
printf("%s; %s; %s; %s\n", $row['date'], $row['min'], $row['max'], $row['avg']);
}
or have the Statement object return the whole array by using
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);

How to select multiple rows from mysql with one query and use them in php

I currently have a database like the picture below.
Where there is a query that selects the rows with number1 equaling 1. When using
mysql_fetch_assoc()
in php I am only given the first is there any way to get the second? Like through a dimesional array like
array['number2'][2]
or something similar
Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.
http://php.net/manual/function.mysql-fetch-assoc.php
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$i=-1;
while($row = mysqli_fetch_array($Subject))
{
$i++;
$SubjectCode[$i]['SubCode']=$row['SubCode'];
$SubjectCode[$i]['SubLongName']=$row['SubLongName'];
}
Here the while loop will fetch each row.All the columns of the row will be stored in $row variable(array),but when the next iteration happens it will be lost.So we copy the contents of array $row into a multidimensional array called $SubjectCode.contents of each row will be stored in first index of that array.This can be later reused in our script.
(I 'am new to PHP,so if anybody came across this who knows a better way please mention it along with a comment with my name so that I can learn new.)
This is another easy way
$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}
Demo Link
It looks like the complete solution has not been suggested yet
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$Rows = array ();
while($row = mysqli_fetch_array($Subject))
{
$Rows [] = $row;
}
The $Rows [] = $row appends the row to the array. The result is a multidimensional array of all rows.

PHP: Unexpected behavior: foreach... {$array['country'][] = $value['country']}

Why does the operator
$array['country'][] return what logically would be $array[]['country']?
What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use
$array['country'][]
despite fact that they are ordered as
$array['row#']['country']
Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?
FULL-ish code here
$result = array();
foreach($data as $value){
$array['country'][] = $value['country'];
$array['report'][] = $value['report'];
}
$data = $array;
Let me know if I am just dumb... I can't really grasp why this is working this way.
get an id from the db
SELECT id,country,report from yourdb
while ($row = mysql_fetch_array($result)) {
$array['country'][$row['id']] = $row['country'];
$array['report'][$row['id']] = $row['report'];
}
create an id
SELECT country,report from yourdb
$i=0
while ($row = mysql_fetch_array($result)) {
$array['country'][$i] = $row['country'];
$array['report'][$i] = $row['report'];
$i++
}
Why does the operator
$array['country'][]
return what
logically would be
$array[]['country']?
It is because you are constructing the array in that way:
If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.
If you want it to map to array[]['country'], then (using part of code from
#Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:
SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
$array[$i]['country'][] = $row['country'];
$array[$i]['report'][] = $row['report'];
$i++;
}
Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.
The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.
So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.
If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.

Categories