trouble with array push in php - 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);

Related

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

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

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

Create and array index and value from the two array elements in a while loop

while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
}
I want an array which has the entries of the array idlist as it's index and entries of the array namelist as it's values.
Is there a short way to do this?
Like this, if I understand your request. Use $info['id'] as the array key to the accumulating array $namelist (or whatever you decide to call it)
while($info5 = mysql_fetch_array($result)){
$namelist[$info['id']] = $info5["name"];
}
i'm not sure i understand your question but probably something like this should be fine.
while($info5 = mysql_fetch_array($result)){
$values[$info5['id']] = $info5;
}
$result = array();
while($info5 = mysql_fetch_array($result))
{
$id = $info5['id'];
$name = $info5['name'];
$result[$id] = $name;
}
This should give the output array $result you want, if I understood correctly.
You can use array_combine as long as the arrays have the same number of values:
$result = false;
if (count($idlist) == count($namelist))
$result = array_combine($idlist, $namelist);
Check out the docs: http://www.php.net/manual/en/function.array-combine.php
But, I also wonder why you don't just do it in the while loop:
$values = array();
$namelist = array();
$idlist = array();
while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
// this is the combined array you want?
$values[$info5["id"]] = $info5["name"];
}

Categories