Append values to its respected array PHP - 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

Related

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);

code is returning data of one date only whereas i want data of every date

function practise()
{
$this->load->database();
$qry = mysql_query("select * from demmo");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$created = $row['created'];
//from here
$qry = mysql_query("select * from demmo where created = '$created'");
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
$users[] = array('user_id' => $user_id, 'name' => $name);
}
$dotts[] = array('created' => $created2);
//till here
}
return array ($dotts,$users);
}
}
in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:
For example, to get all of the dates:
$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
array_push($dotts, $created2);
$users[] = array('user_id' => $user_id, 'name' => $name);
array_push($allusers, $users);
}
//
return array ($dotts,$allusers);
You need to create an array and use array_push function , then only it will have more than one value.
example:
create an empty array as
$allUser = array();
then after this line
$users[] = array('user_id' => $user_id, 'name' => $name);
use array_push as
array_push($allUser, $users);
}
return array($dots, $allUser);

Array problems with JSON in 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();

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

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