Add additional element to array - php

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;

Related

PHP Creating an array inside a For Loop

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.

while-Loop in foreach-Loop with mysqli_query leads to unexpected result

I have a pice of code to get data from a mysql database. I need to build containers for all stations with the same station_group which I do via a foreach loop. Inside the foreach-loop, there is a while loop to fill the station group containers with all the stations that have the parents station_group. The code works fine if I have debbugging echo lines in the code (so some kind of delay), but having them commented out, the code delivers wrong order of containers and stations. I gues its because of the asynchronous function fetch_assoc so I might put in a callback function, but I just don't get it runnig. Therefore I would appriciate any help... =)
BR
<?php
//build unique Station group array
$sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
$unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group, station_id ASC";
$result= mysqli_query($dbConn, $sql);
//Loop for station_group
foreach ($unique_station_groups as $station_group_value){
echo '<div class="css-station-group>';
while ($row = mysqli_fetch_assoc($result)) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group_value['station_group']==$station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
}
}
echo '</div>';
mysqli_data_seek($result,0); //reset array, so next Loop will find values again
}
?>
You don't need two queries to do this.
Store the previous station_group and check the current_group and previous group to differentiate the stations.
Changed your code a bit
<?php
//build unique Station group array
// $sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
// $unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group ASC";
$result= mysqli_query($dbConn, $sql);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
//Loop for station_group
// foreach ($unique_station_groups as $station_group_value) {
$current_station_group = null;
echo '<div class="css-station-group">';
foreach ($rows as $row) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group != $current_station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
$current_station_group = $row['station_group'];
}
}
echo '</div>';
?>
It looks like it might be easier to simply dump the results in an array then loop through the array.
<?php
//build unique Station group array
$sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
$unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group, station_id ASC";
$result= mysqli_query($dbConn, $sql);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
//Loop for station_group
foreach ($unique_station_groups as $station_group_value){
echo '<div class="css-station-group>';
foreach ($rows as $row) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group_value['station_group']==$station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
}
}
echo '</div>';
}
?>

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

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.

PHP loop syntax issues

I need to add a counter to the loop as well as pulling contents. What is the syntax for adding the "and for ($ColCount = ColCount + 1)"
<?php $ColCount = 0?>
<!--get artwork thumbnails -->
<?php
$dbname = 'pdartist2';
$table = 'artwork';
// query
$result = mysql_query("SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '$SCID' ") or die(mysql_error());
while($row = mysql_fetch_row($result))
{
foreach($row as $cell)
and for ($ColCount = ColCount + 1)
echo "$ColCount", "$cell";
}
mysql_free_result($result);
?>
I have no idea if that's valid in PHP. Maybe all it is is a forgotten $ sign before ColCount. But you could just do it the normal way:
foreach($row as $cell) {
$ColCount++;
echo $ColCount . $cell;
}
$ColCount = 0;
Code:
<!--get artwork thumbnails -->
<?php
$dbname = 'pdartist2';
$table = 'artwork';
// query
$result = mysql_query("SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '$SCID' ") or die(mysql_error());
while($row = mysql_fetch_row($result))
{
$colCount = 0;
foreach($row as $cell) {
$colCount++;
echo "$ColCount", "$cell";
}
}
mysql_free_result($result);
?>
As Bruce said, you could just do $ColCount++, But also you could just count the results with mysql_num_rows
$result = mysql_query("SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '$SCID' ") or die(mysql_error());
$numRows = mysql_num_rows($result);
Shai
You are missing a semi-colon:
<?php $ColCount = 0?>
Should be:
<?php $ColCount = 0; ?>
And:
while($row = mysql_fetch_row($result)) {
foreach($row as $cell) {
$ColCount++; // adds 1 to colcount
echo $ColCount.$cell; // no need for quotes around variables. Also string concatination in PHP is using s dot (.)
}
}
mysql_free_result($result);
What i'll do is use an array like that
<!--get artwork thumbnails -->
<?php
$dbname = 'pdartist2';
$table = 'artwork';
# Define array
$Count = array();
// query
$result = mysql_query('SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '.$SCID) or die(mysql_error());
while($row = mysql_fetch_row($result)){
foreach($row as $cell){
$Count[$Cell]['Count'] = $Count[$Cell]['Count']++;
}
echo $ColCount.', '.$cell;
}
mysql_free_result($result);
So you have the count for each colomn but what I suggest is to use the mysql_num_rows(); like that :
$Query = mysql_query...
$Count = mysql_num_rows($Query);
$Count will be a number ;)
Then if($Count > 0)
If you're trying to count the number of columns in each row, then
while($row = mysql_fetch_row($result)) {
$colCount += count($row);
}
though I fail to see point of this. an SQL result set is a perfectly rectangular array. Variable number of rows, but every row will ALWAYS have the same number of fields as all the other rows in the result set. You'd only have to count the columns ONCE and cache that value.

Categories