Printing out associative arrays fetched from SQL database - php

I have fetched 3 arrays out of a database and put them in associative arrays.
I have learned to print out array as shown below in the comments, but this doesn't seem to work? How can I achieve this?
while($row = mysql_fetch_array($query)) //fetching row in db
{
$weight = $row['weight'];
$height = $row['height'];
$bmi = round($weight / (pow(($height/100),2)),2); //calculates bmi
$arrName[] = $row['name']; //main name array
$arrGender[] = array($row['name'] => $row['gender']); //this and below are associative arrays
$arrBmi[] = array($row['name'] => $bmi);
}
foreach($arrName as $key=>$value){
echo "$value is of gender {$arrGender[$value]} and has a bmi of {$arrBmi[$value]}"; //this line
}

Like this instead:
$arrGender[$row['name']] = $row['gender']
$arrBmi[$row['name']] = $bmi);
The way you're doing it, you're assigning multiple sub-arrays to numeric indexes instead of using the name as the key. One thing to watch out for if you end up doing it this way is that if there are non-unique names in your query result, the value at that array key will be overwritten for subsequent duplicate names.
It doesn't look like your really need the second loop, though. You can output the same thing in the while loop as you fetch the results:
while ($row = mysql_fetch_array($query)) //fetching row in db
{
$bmi = round( $row['weight'] / (pow(( $row['height'] /100),2)),2); //calculates bmi
echo "$row[name] is of gender $row[gender] and has a bmi of $bmi"; //this line
}

This is a weird array to construct and I would simplify it, but use the $key and the name ($value) to access the others:
echo "$value is of gender {$arrGender[$key][$value]}
and has a bmi of {$arrBmi[$key][$value]}";
To keep it simple just use the array as it comes from the fetch:
$array[] = ['name' => $row['name'],
'gender' => $row['gender'],
'bmi' => $bmi];
Then in the loop:
echo "{$value['name']} is of gender {$value['gender']}
and has a bmi of {$value['bmi']}";

Related

PHP: Get element of an array

I have an element stored in the following way:
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["data"]. "</td></tr>";
$data1= floatval($row["data"]);
...
It is a value extracted from a MySQL database, and thus it is stored this way. If I want to get the value of the iteration let's say "i", it is easy, as I do not have to do anything else but how can I obtain the following value in order to perform a substraction? That's to say, data2 - data1? I thought about something similar to $row["data"][i], but I'm not sure it'll work. Thanks!
As you can see in the manual of fetch_assoc this function fetches only one row at a time and that's why we're using a loop.
The same goes for fetch_array and fetch_row.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
The only solution that I can think of is to loop that array and to store that data in another array according to your requirements, for instance:
$customArr = array();
$i = 0; //counter.
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["data"]. "</td></tr>";
$data1= floatval($row["data"]);
$customArr[$i] = array('id' => $row['id'], 'date' => $date1);
}
Later on, if you want to compare values in the array you should use while and index-based scenarios like $customArr[$i-1], $customArr[$i].
Just make sure that you check the offset.
$i = 0;
while($i < count($customArr)){
}

PHP - Multidimensional Array

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

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'];
}

Sort array according to value of key

I have one array which have the right order of the keys,
For example,
$array_keysorder=([0]=>"Fire",[1]=>"Sky",[2]=>"Third")
//Array i want to sort,after appending the order is messed up
$tosortarray=(['Sky']=>array(array()...),['Third']=>array(),['Fire']=>array())
//This is how i want the final array to look like
$Final=(['Fire']=>array(), ['Sky']=>array(array()...),['Third']=>array())
What about rebuilding the array?
Edit.. I added some commenting..
<?php
$array_keysorder[] = "Fire";
$array_keysorder[] = "Sky";
$array_keysorder[] = "Third";
print_r($array_keysorder);
$bad_array[Sky] = "data1";
$bad_array[Third] = "data2";
$bad_array[Fire] = "data3";
echo "<br>";
print_r($bad_array);
//This count cycles through the sort order, 0 = Fire, 1 = Sky, etc.
$key = 0;
//Cycle through array. $row isn't used.
foreach($bad_array as $row)
{
//$temp_val will store the key name ie "Fire".
$temp_val = $array_keysorder[$key];
//Create a organized array with the correct order of the keys
$good_array[$temp_val] = $bad_array[$temp_val];
//Increase the key to the next one.
$key++;
}
echo "<br>";
print_r($good_array);
?>

PHP Multi Dimension Array Assignment

I need to fill a multidimensional array and here is my code I have so far for it.
while($num > $i)
{
$default[$i]=0;
$defaultcounter=0;
$default2[$i]=0;
$default3[$i]=0;
$query="Select * from `issues` WHERE `app`='" . $applist[$i] . "'" . "AND `startmonth`='". $month ."' ORDER BY `id` ASC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result))
{
$downtime[$i]+=$row['duration'];
$default2[$i]++; //Number of Incidents Variable
$defaultcouinter++;
$times[$i] = array();
$times[$i][$defaultcounter[$i]]=$row['startday'].$row['starttime'];
}
$appavail[$i]=100 -(ceil($downtime[$i] * 100 / $totaltime));
$default[$i] = (ceil($downtime[$i] / $defaultcounter));
$i++;
}
Apparently I am not doing the array assignment correct. I need to to have my number of rows counted with the $i variable outside of my while then inside the while the defaultcounter will be keeping up with the column. I tried just doing a $time[$i][defaultcounter] and it didn't like it. Whats the proper syntax for assigning a multidimensional array?
Thanks
$times[$i] = array() should be out (before) the while loop unless you want it redefining $times as an empty array in each iteration (reseting values). Apart from that, you're assigning the values correct, although it looks a bit odd (not sure what you want to achieve there). This are the general formulas, should give you an idea:
$array[] = $subarray;
$array[$subarray] = $value;
$array[$subarray][] = $value;
$array[$subarray][$i] = $value;

Categories