PHP Creating an array inside a For Loop - php

Looking for some help if possible.
$pilotsids is an array of ids.
merged is the table that holds the data.
For each pilotid, I'd like to create an array of newrat values, which I am going to use later to populate a chart. The index of the for loop must be added to the name of each array like this:
$data0[]
$data1[]
$data2[]...etc
It works when I do it separately:
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[0] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data0[] = $row['newrat'];
}
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[1]' order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data1[] = $row['newrat'];
}
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[2]' order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data2[] = $row['newrat'];
}
It doesn't if I try to to iterate automatically for lets say 10 times:
for($i=0; $i < 10; $i++) {
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
${$data.$i}[] = $row['newrat'];
}
}

You can try this way:
$data = [];
for($i=0; $i < 10; $i++) {
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data[$i][] = $row['newrat'];
}
}
As you can see I'm using a two dimensional array which is defined outside of the loop.

Related

How to merge an array inside another array in php?

Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php

Merging arrays to the one array from while loop

I need an information to put from DB to arrays and then make one array.
So I wrote a following code:
$sql0 = "SELECT * FROM ".$working_table." ORDER by id ASC";
$result = mysqli_query($conn, $sql0);
$num_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
${"emails_arr$row[id]"} = explode(",",$row['station_email']);
echo print_r(${"emails_arr$row[id]"})."<br>";
}
$sql0 = "SELECT * FROM ".$working_table." ORDER by id ASC";
$result = mysqli_query($conn, $sql0);
$num_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
$result_array = array_merge(${"emails_arr$row[id]"});
}
echo print_r($result_array);
the tricky part is that i don't know how to merge an arrays to one array from the while loop: $result_array = array_merge(${"emails_arr$row[id]"});
it only shows the last array, other arrays are being rewrote.
Thank you guys!
Change your while loop code with this one
while($row = mysqli_fetch_array($result)){
$result_array[] = array_merge(${"emails_arr$row[id]"});
}
Notice the Square Brackets.

Add additional element to array

If I have an array $MovieDetails = array(); and it is populated by the query below with a foreach loop (5 elements; id, movie_year, genre, image, movie_name), how do I add another element (movie_rating) to the end of the array
$AllMovies = $con ->query
("
SELECT id, movie_year, genre, image, movie_name FROM movies;
");
while($row = $AllMovies->fetch_object()) {
$MovieDetails[] = $row;
}
Add movie rating into $row.
If you work with that as object, it's $row->movie_rating = 1.5
while($row = $AllMovies->fetch_object()) {
$row->movie_rating = 1.5;
$MovieDetails[] = $row;
}
If you work with that as array, use fetch_assoc() and $row['movie_rating'] = 1.5
while($row = $AllMovies->fetch_assoc()) {
$row['movie_rating'] = 1.5;
$MovieDetails[] = $row;
}
This way your row is an object
$AllMovies = $con->query("SELECT id, movie_year, genre, image, movie_name FROM movies;");
while($row = $AllMovies->fetch_object()) {
$row->movie_rating = 'movieRating';
$MovieDetails[] = $row;
}
If you want each row to be array, you should do:
while($row = $AllMovies->fetch_array()) {
$row['movie_rating'] = 'movieRating';
$MovieDetails[] = $row;
}
$MovieDetails['movie_rating'] = $movie_rating;

Adding to an array from $row

How do I add each result from $row to the $valueIDArray? I then want to use the $valueIDArray to get results from a second database, how do I do that?
$sql = "SELECT * FROM venue
WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
while($row = $result -> fetchrow()){
$valueIDArray = $row[0];
}
You should do it this way:
$valueIDArray = array()
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
Define array before loop, and in loop simple add elements to array using [] after array name
$sql = "SELECT * FROM venue WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
$valueIDArray = array();
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
You have to add the [] braces. Like this, you always add another entry for the row.

storing percentages into an array

I'm trying to store a number of percentages that I've worked out into an array so that I can call it later on to create a pie chart but don't have a clue how to do it. Here is my PHP code so far for working out the percentages: Thanks for any help in advance!
//execute the SQL query and return records
$result = mysql_query("SELECT book_id, COUNT(*) FROM loan GROUP BY book_id ASC ORDER BY count(*) DESC LIMIT 10");
$book_count = mysql_num_rows($result);
$step = 1;
while($row = mysql_fetch_array($result))
{
$total = $total + $row['COUNT(*)'];
$i[$step] = $row['COUNT(*)'];
$step++;
}
for($index = 1; $index <= 10; $index++)
{
$percentage[$index] = (($i[$index]/$total)*100);
#$degrees = (($percentage/100)*360);
}
This should do what you're asking, just substitute the variables for real ones:
array_push($array, $value);
// This will add "$value" on to the end of $array, i.e the last element
It can also be done much simpler:
$array[] = $value;
Updated code:
//execute the SQL query and return records
$result = mysql_query("SELECT book_id, COUNT(*) FROM loan GROUP BY book_id ASC ORDER BY count(*) DESC LIMIT 10");
$book_count = mysql_num_rows($result);
$step = 1;
while($row = mysql_fetch_array($result))
{
$total = $total + $row['COUNT(*)'];
$i[$step] = $row['COUNT(*)'];
$step++;
}
$percentage_array = array();
for($index = 1; $index <= 10; $index++)
{
array_push($percentage_array, (($i[$index]/$total)*100));
#$degrees = (($percentage/100)*360);
}

Categories