How can I refactor this hideous beast? - php

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

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

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

PHP, getting different array value from different foreach

I'm quite lost, in the following code:
while($row = mysqli_fetch_object($result)){
$similar_games[$row->game_id]['id'][] = $row->id;
$similar_games[$row->game_id]['name'][] = $row->name;
$similar_games[$row->game_id][$type] = 0;
}
foreach($similar_games as $originalGameKey => $originalGame){
//Can be a case where union gets unset, and not populated. scares ksort();
$union = array();
$similar_values = array();
$union = $similar_concepts;
foreach($originalGame['id'] as $similarGameKey => $similarGame){
if(!isset($union[$similarGame])){
$union[] = $similarGame;
}
}
foreach($originalGame['id'] as $similarGameKey => $similarGame){
if(isset($union[$similarGame])){
$similar_values[] = $similarGame;
}
}
$similar_games[$originalGameKey]["union"] = $similar_values;
}
At the line $similar_values[] = $similarGame; I'm attempting to get the $row->name rather than the $row->id
But I don't know how to make the foreach which is based on the ['id'] access the ['name'] values.
If this is too confusing, I can try to clarify, but I'm having trouble here myself.
I just changed:
foreach($originalGame['id'] as $similarGameKey => $similarGame){
if(isset($union[$similarGame])){
$similar_values[] = $similarGame;
}
}
$similar_games[$originalGameKey]["union"] = $similar_values;
To:
for($i = 0; $i<count($originalGame['id']);$i++){
if(isset($union[$originalGame['id'][$i]])){
$similar_values[] = $originalGame['name'][$i];
}
}
$similar_games[$originalGameKey]["union"] = $similar_values;

Dynamic Content in PHP array

This should be a quick one.
I'm pulling a list of id's and I need to place them in an array.
Here is my php code to get the list of id's
$get_archives = mysql_query("SELECT * FROM archive WHERE user = '$email' ");
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id = $row['insta_id'];
$insta_id = "'" . $insta_id."',";
echo $insta_id;
};
This echo's a list of id's that looks like this: '146176036','136514942',
Now I want to put that list into an array. So i tried something like this:
$y = array($insta_id);
However that isn't working. Any suggestions?
$y = array();
while ($row = mysql_fetch_assoc($get_archives)) {
$y[] = $row['insta_id'];
}
$myArray = array();
$get_archives = mysql_query("SELECT * FROM archive WHERE user = '$email' ");
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id = $row['insta_id'];
$insta_id = "'" . $insta_id."',";
$myArray[] =$insta_id;
};
did you mean like this: ?
$insta_id=array();
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id[] = $row['insta_id'];
}
Create an array, and push the values into it:
$values = array();
while ( $row = mysql_fetch_assoc( $get_archives ) ) {
array_push( $values, $row['insta_id'] );
}

Categories