Array problems with JSON in PHP - php

I'm trying to output a JSON feed in PHP and I keep having an issue where the second result in the JSON feed includes the results of the first as well.
Source below, and output:
Source
function fetch_tour_list($tourID) {
include('../inc/conn.php');
$query = mysqli_query($conn,"SELECT * FROM ticket_tour_dates WHERE TourID = $tourID");
while($result = mysqli_fetch_array($query)) {
$date['date'] = $result['Date'];
$venueID = $result['VenueID'];
$venue_query = mysqli_query($conn,"SELECT * FROM ticket_venues WHERE ID = $venueID");
while($venue_result = mysqli_fetch_array($venue_query)) {
$venue['id'] = $venue_result['ID'];
$venue['name'] = $venue_result['Name'];
$venue['location'] = $venue_result['Location'];
$venue['latitude'] = $venue_result['Lat'];
$venue['longitude'] = $venue_result['Long'];
$venues[] = $venue;
}
$date['venue'] = $venues;
$dates[] = $date;
}
echo json_encode($dates);
mysqli_close($conn);
}
Output
[{"date":"2013-07-29","venue":[{"id":"1","name":"The Gramercy","location":"New York City","latitude":"50.00000000","longitude":"50.00000000"}]},{"date":"2013-08-02","venue":[{"id":"1","name":"The Gramercy","location":"New York City","latitude":"50.00000000","longitude":"50.00000000"},{"id":"2","name":"The Troubadour","location":"Chicago","latitude":"20.00000000","longitude":"25.00000000"}]}]

Add the following line before the inner while loop:
$venues = array();

Related

Append values to its respected array PHP

I have my response where I want to fill below.
$response = array(
"year" => array(),
"playerName" => array(),
"cardVariation" => array()
);
I have a simple query to my table.
$sql = "SELECT * from $TBL";
$result = $conn->query($sql);
I will then lop through my results.
while($row = $result->fetch_assoc()) {
$year = $row['year'];
$playerName = $row['name'];
$cardVariation = $row['cardV'];
// add to response
$response['year'] = $year;
$response['name'] = $playerName;
$response['cardV'] = $cardVariation;
}
echo json_encode($response);
Expected response:
{"year": ["1999", "2000"], "name": ["bill", "jess"], "cardV": ["base","silver"]}
Only the last one gets added. I couldn't find an "append" method for PHP, unless i looked over it.
You are over writing the values each time round the loop so place the values into a new occurance each time by using $response['year'][] = . Also you are wasting time moving values into scalar variables.
while($row = $result->fetch_assoc()) {
// add to response
$response['year'][] = $row['year'];
$response['name'][] = $row['name'];
$response['cardV'][] = $row['cardV'];
}
You can use array_push() or just
$response['year'][] = $year;
$response['name'][] = $playerName;
$response['cardV'][] = $cardVariation;
https://www.php.net/manual/de/function.array-push.php

PHP is filling json with duplicates of last item

I am working on a web app using php. I am trying to pull from a database and fill an array with the information then encode it to json.
Here is what I have so far:
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
$frats[] = $frat;
}
echo json_encode($frats);
What I get in return is in the correct json format I want with the correct keys and everything, but every item in the json is the same. All of them are the last one. I believe this is because I might just be referencing the values, but I am not sure how to actually copy them in php.
Any suggestions?
you need to create a new instance of $frat inside the loop. Otherwise you are just updating the original $frat each time the loop runs and adding a reference to it in the array.
Assuming its not a static class you could use:
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat = new frat();
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
$frats[] = $frat;
}
echo json_encode($frats);
Even better would be to modify the constructor or create a method to consume the data. If you used the class's constructor then you could do something like this:
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frats[] &= new frat($row['name'], $row['description'], $row['chapter']);
}
echo json_encode($frats);
In the first line inside your while loop, you simply need the following line:
$frat = new \stdClass();
You need to properly declare your variables $frats (array) and $frat (object):
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat = (object) array();
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
array_push($frats, $frat); // For backward compatiblity
}
echo json_encode($frats);

How can I refactor this hideous beast?

I have a query that I execute, then I use
while($row = $result->fetch_assoc()){
$data[] = $row;
I know this is grotesque, but I'm unsure how to make this an object or a multidimensional array so I just made something like this..
$NUH2016 = array();
$NUH2017 = array();
$NUH2018 = array();
$NUH2019 = array();
$NUH2020 = array();
$NUH2021 = array();
$RBN2016 = array();
$RBN2017 = array(); ...
...$GDT2019 = array();
$GDT2020 = array();
$GDT2021 = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
if($row['Location'] == 'NUH' && $row['Year'] == '2016'){
$NUH2016[] = $row['P_1'];
$NUH2016[] = $row['P_2'];
$NUH2016[] = $row['P_3'];
$NUH2016[] = $row['P_4'];
}
if($row['Location'] == 'NUH' && $row['Year'] == '2017'){
$NUH2017[] = $row['P_1'];
$NUH2017[] = $row['P_2'];
$NUH2017[] = $row['P_3'];
$NUH2017[] = $row['P_4'];
}
//...for all locations and years
...then
$content = array();
$results = array();
$NUH2016_total = array_sum($NUH2016);
$NUH2017_total = array_sum($NUH2017);
$NUH2018_total = array_sum($NUH2018);
$NUH2019_total = array_sum($NUH2019);
$NUH2020_total = array_sum($NUH2020);
$NUH2021_total = array_sum($NUH2021);
$results['NUH~2016'] = $NUH2016_total;
$results['NUH~2017'] = $NUH2017_total;
$results['NUH~2018'] = $NUH2018_total;
$results['NUH~2019'] = $NUH2019_total;
$results['NUH~2020'] = $NUH2020_total;
$results['NUH~2021'] = $NUH2021_total;
$RBN2016_total = array_sum($RBN2016);
$RBN2017_total = array_sum($RBN2017);
$RBN2018_total = array_sum($RBN2018);
$RBN2019_total = array_sum($RBN2019);
$RBN2020_total = array_sum($RBN2020);
$RBN2021_total = array_sum($RBN2021);
$results['RBN~2016'] = $RBN2016_total;
$results['RBN~2017'] = $RBN2017_total;
$results['RBN~2018'] = $RBN2018_total;
$results['RBN~2019'] = $RBN2019_total;
$results['RBN~2020'] = $RBN2020_total;
$results['RBN~2021'] = $RBN2021_total;
...etc
$content['Results'] = $results;
$response = json_encode($content);
echo $response;
So what I want to do is make an object or associative array that looks like this.
content {
produced hours{
nuh{ 2016:16,000
2017:8,000
...
}
rbn{ 2016:9,000
2017:whatever
....
}
man hours{
nuh{ 2016:4,000
2017:2,000
...
}
rbn{ 2016:1,000
2017:more stuff
....
}
but I'm pretty new to php objects. How can I refactor it so that I don't have to initialize every single empty array, have a bunch of if statements to make each entry from the query fit into an array to be summed, and then put it all into an object at the end to get back from an ajax success function?
There's no need to declare so many arrays. Simply change your while() loop in the following way,
$resultArr = array();
while($row = $result->fetch_assoc()){
$tmpArr = array($row['P_1'], $row['P_2'], $row['P_3'], $row['P_4']);
$sumTotal = array_sum($tmpArr);
$tmpArr['sumTotal'] = $sumTotal;
$resultArr[$row['Location']][$row['Year']][] = $tmpArr;
}
Later, apply json_encode() on the result array like this,
$json = json_encode($resultArr);
Sidenote: If you want to see the complete array structure, do var_dump($resultArr);
You can have an array of arrays, so you don't need to manually assign them all.
$LocationAndYears;
while($row = $result->fetch_assoc())
{
$LocationAndYears[$row['Location']] [$row['Year']] [0] = $row['P_1'];
$LocationAndYears[$row['Location']] [$row['Year']] [1] = $row['P_2'];
$LocationAndYears[$row['Location']] [$row['Year']] [2] = $row['P_3'];
$LocationAndYears[$row['Location']] [$row['Year']] [3] = $row['P_4'];
$LocationAndYears[$row['Location']] [$row['Year']] ['sum'] = array_sum($LocationAndYears[$row['Location']] [$row['Year']]);
}
echo $LocationAndYears['NUH']['2012'][0];
echo "Sum for 2012 at NUH:" . $LocationAndYears['NUH']['2012']['sum'];
print_r($LocationAndYears);
Without writing the whole thing, look into multi-dimensional arrays.
Something like this maybe...
But really I think the answer to this is to point you at multi-dimensional arrays as it's very vague
$data = array();
while($row = $result->fetch_assoc()){
$location = $row['Location'];
$year = $row['Year'];
$data[$location] = $data[$location] ? $data[$location] : array();
$data[$location][$year] = $data[$location][$year] ? $data[$location][$year] : array();
$data[$location][$year][] = $row['P_1'];
$data[$location][$year][] = $row['P_2'];
$data[$location][$year][] = $row['P_3'];
$data[$location][$year][] = $row['P_4'];
}

trouble with array push in php

I have a problem with array push.I cant get the all data from the array array.I want to get like this format.
[["username","average"],["aa",2.34],["bb",6.7],["hh",9.8]]
here is my code
while($acc_rs = mysql_fetch_array($acc_qry))
{
$acc_cnt = $acc_rs['Total_login'];
$time_stamp = $acc_rs['last_logged'];
$avg_login = $acc_rs['avg'];
$name = $acc_rs['name'];
$ji = array();
$sal = array("username","average");
$kk = array($name,$avg_login);
array_push($ji,$sal,$kk);
}
array_push($da,$new,$average);
$result = array(array('username', 'average'));
while ($row = mysql_fetch_assoc($acc_qry)) {
$result[] = array($row['name'], $row['avg']);
}
echo json_encode($result);

Formatting information in a PHP recordset and setting it to an Array

I am attempting to use a Manager Class to take the results of a query and do formatting on pieces of information so I don't have to have logic on my view. I googled a number of solution and thought this would work, but my Array of Key=>values is coming back blank. Can someone take a look at it and see what i am doing wrong? Thanks!
I have verified that $results contains the values I am attempting to format and place back into an Array.
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']] = $row['petID'];
$pets[$row['chipID']]=$row['chipID'];
$pets[$row['adoptionDate']]=Date($row['adoptionDate'],'m-d-Y');
$pets[$row['pType']]=$row['pType'];
$pets[$row['breedName2']]=$row['breedName2'];
$pets[$row['breedName1']]=$row['breedName1'];
$pets[$row['imageName']]=$row['imageName'];
$pets[$row['intakeDate']]= Date($row['intakeDate'],'m-d-Y');
$pets[$row['status']]=$row['status'];
$pets[$row['age']]=$row['age'];
$pets[$row['ageText']]= $this->getAge($row['age']);
$pets[$row['gender']]=$row['gender'];
$pets[$row['genderText']] = $this->getGender($row['gender']);
$pets[$row['breed2']]=$row['breed2'];
$pets[$row['breed']]=$row['breed'];
$pets[$row['petType']]=$row['petType'];
$pets[$row['petName']]=$row['petName'];
$pets[$row['customID']]=$row['customID'];
}
Here is the complete function that does not return anything:
public function getPets($cond,$orgID){
$pets = array();
$pg = new petsGateway();
$results = $pg->listByQuery($cond, $orgID);
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']] = $row['petID'];
$pets[$row['chipID']]=$row['chipID'];
$pets[$row['adoptionDate']]=Date($row['adoptionDate'],'m-d-Y');
$pets[$row['pType']]=$row['pType'];
$pets[$row['breedName2']]=$row['breedName2'];
$pets[$row['breedName1']]=$row['breedName1'];
$pets[$row['imageName']]= $this->getImageURL($row['imageName']);
$pets[$row['intakeDate']]= Date($row['intakeDate'],'m-d-Y');
$pets[$row['status']]=$row['status'];
$pets[$row['age']]=$row['age'];
$pets[$row['ageText']]= $this->getAge($row['age']);
$pets[$row['gender']]=$row['gender'];
$pets[$row['genderText']] = $this->getGender($row['gender']);
$pets[$row['breed2']]=$row['breed2'];
$pets[$row['breed']]=$row['breed'];
$pets[$row['petType']]=$row['petType'];
$pets[$row['petName']]=$row['petName'];
$pets[$row['customID']]=$row['customID'];
}
return $pets;
}
That's rather... repetitive code... wouldn't it be easier to modify your query to fetch the rows you want AND do the date formatting directly in the DB?
e.g.
SELECT rowID, ... DATE_FORMAT(adoptionDate, '%m-%d-%Y'), ...
FROM ...
and then
while($row = mysql_fetch_assoc($result)) {
$pets[] = $row;
}
hm.... well im not sure what you want, but as you have it now, the key and the value of your array will be the same, which makes it useless.
i.e. for petName
$pets['Fido'] = 'Fido'
probably you want to get rid of the $row portion of the left side of your assignment, so that you end up with this
while($row = mysqli_fetch_array($results))
{
$pet = Array();
$pet['petID'] = $row['petID'];
$pet['chipID'] = $row['chipID'];
$pet['adoptionDate'] = Date($row['adoptionDate'],'m-d-Y');
$pet['pType'] = $row['pType'];
$pet['breedName2'] = $row['breedName2'];
$pet['breedName1'] = $row['breedName1'];
$pet['imageName'] = $row['imageName'];
$pet['intakeDate'] = Date($row['intakeDate'],'m-d-Y');
$pet['status'] = $row['status'];
$pet['age'] = $row['age'];
$pet['ageText'] = $this->getAge($row['age']);
$pet['gender'] = $row['gender'];
$pet['genderText'] = $this->getGender($row['gender']);
$pet['breed2'] = $row['breed2'];
$pet['breed'] = $row['breed'];
$pet['petType'] = $row['petType'];
$pet['petName'] = $row['petName'];
$pet['customID'] = $row['customID'];
$pets.push($pet);
}
I am guessing but I understood that you want some thing like:
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']]['petID'] = $row['petID'];
$pets[$row['petID']]['chipID'] = $row['chipID'];
$pets[$row['petID']]['adoptionDate'] = Date($row['adoptionDate'],'m-d-Y');
$pets[$row['petID']]['pType'] = $row['pType'];
$pets[$row['petID']]['breedName2'] = $row['breedName2'];
$pets[$row['petID']]['breedName1'] = $row['breedName1'];
$pets[$row['petID']]['imageName'] = $row['imageName'];
$pets[$row['petID']]['intakeDate'] = Date($row['intakeDate'],'m-d-Y');
$pets[$row['petID']]['status'] = $row['status'];
$pets[$row['petID']]['age'] = $row['age'];
$pets[$row['petID']]['ageText'] = $this->getAge($row['age']);
$pets[$row['petID']]['gender'] = $row['gender'];
$pets[$row['petID']]['genderText'] = $this->getGender($row['gender']);
$pets[$row['petID']]['breed2'] = $row['breed2'];
$pets[$row['petID']]['breed'] = $row['breed'];
$pets[$row['petID']]['petType'] = $row['petType'];
$pets[$row['petID']]['petName'] = $row['petName'];
$pets[$row['petID']]['customID'] = $row['customID'];
}
This way you have an array with all the pets ID as first key and its details in the second key. You can use the array push as well.
That will rewrite $pets[KEY] each time it loops through record. You want..
$pets[]['petID'] = $row['petID'];
$pets[]['chipID'] = $row['chipID'];
and so on

Categories