Generating Graph with 2 Y Values from Text File - php

I have remade my original post as it was terribly formatted. Basically I would like some advice / tips on how to generate a line graph with 2 Y Axis (temperature and humidity) to display some information from my text file. It is contained in a textfile called temperaturedata.txt I have included a link to one of my posts from the JpGrapher forum only because it is able to display the code clearly.
I understand that since it is JpGraph problem I shouldn't post here however the community here is a lot more supportive and active. Many thanks for all your help guys in advance!
my code

I don't see any reason why you shouldn't post here about jpgraph. And I don't see why you shouldn't post your sample code and data here, either.
The code you've posted on the other site is broken. Check line #42.
Furthermore, you're passing JpGraph a single row (specifically, the last row) via $keyval. $data is where all your data is stored, though in a wrong format. A very quick fix was:
$keyval = array();
$keyval['time'] = array();
$keyval['count'] = array();
$keyval['temperature'] = array();
$keyval['humidity'] = array();
if ($file) {
while (!feof($file)) {
$line = trim(fgets($file));
if (strlen($line)) {
$fields = explode(":", $line);
$keyval['time'][] = $fields[0];
$keyval['count'][] = $fields[1];
$keyval['temperature'][] = $fields[2];
$keyval['humidity'][] = $fields[3];
}
}
fclose($file);
}
which transposed $data and renamed it $keyval. (Where it used to hold time data in $data[x]['time'], it now holds it in $keyval['time'][x].) And we're passing $keyval['temperature'], which is a simple array of temperature values.

Related

Export php array to json with a specific structure (google charts)

I'm trying to use the google charts api to present power (watt) over time. I have a sqlite database in which i store my data. A php script then gathers the data and outputs it into a json file. For the charts to work i need to keep a specific structure. Whenever i run the phpscript the json file gets overwritten with the new data. I need help with the php script to always output the data according to googles parameters.
I'm aiming to end up with an area chart that plots power on the y axis and the datestamps on the x axis.
I've read theese documents in googles documentation but i can't figure out how to output the data the way they do.
https://developers.google.com/chart/interactive/docs/php_example
https://developers.google.com/chart/interactive/docs/reference#dataparam
while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){
$voltage[] = $res['voltage'];
$current[] = $res['current'];
$datestamp[] = $res['datestamp'];
}
$unixtimestamp = array();
foreach ($datestamp as $nebulosa){
$unixtimestamp[] = strtotime($nebulosa);
}
$power = array();
foreach ($voltage as $key => $door){
$power[] = $door * $current[$key];
}
//echo "<pre>", print_r($power, true), "</pre>";
$fp = fopen('data.json', 'w');
fwrite($fp, json_encode($power));
fwrite($fp, json_encode($datestamp));
fclose($fp);
The json file has this format after running the php script.
[3.468,5]["2016-10-14 14:56:22","2016-10-14 14:56:23"]

Getting all from json api array using php

I wanna improve on how to fetch data from an API. In this case I want to fetch every app-id from the Steam API, and list them one per line in a .txt file. Do I need an infinite (or a very high-number) loop (with ++ after every iteration) to fetch everyone? I mean, counting up from id 0 with for example a foreach-loop? I'm thinking it will take ages and sounds very much like bad practice.
How do I get every appid {"appid:" n} from the response of http://api.steampowered.com/ISteamApps/GetAppList/v0001?
<?php
//API-URL
$url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
//Fetch content and decode
$game_json = json_decode(curl_get_contents($url), true);
//Define file
$file = 'steam.txt';
//This is where I'm lost. One massive array {"app": []} with lots of {"appid": n}.
//I know how to get one specific targeted line, but how do I get them all?
$line = $game_json['applist']['apps']['app']['appid'][every single line, one at a time]
//Write to file, one id per line.
//Like:
//5
//7
//8
//and so on
file_put_contents($file, $line, FILE_APPEND);
?>
Any pointing just in the right direction will be MUCH appreciated. Thanks!
You don't need to worry about counters with foreach loops, they are designed to go through and work with each item in the object.
$file = "steam.txt";
$game_list = "";
$url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
$game_json = file_get_contents($url);
$games = json_decode($game_json);
foreach($games->applist->apps->app as $game) {
// now $game is a single entry, e.g. {"appid":5,"name":"Dedicated server"}
$game_list .= "$game->appid\n";
}
file_put_contents($file, $game_list);
Now you have a text file with 28000 numbers in it. Congratulations?

PHP: Taking Array (CSV) And Intelligently Returning Information

Hey Everyone. I'm a first time poster, but I've browsed this site a number of times. I have a coding issue that I'm not sure exactly how to solve. First I'll explain what I need to do, and what information I have, and I hope somebody can give me a nudge in the right direction.
What I have is a spreadsheet (CSV) that has the following info: Zone Name, Zip Code, City Name. One zone should have many cities that fall under it, and every city most likely has many zip codes that fall under it. For example:
Zone H, 92603, Irvine
Zone H, 92604, Irvine
Zone J, 92625, Corona
etc.
Okay, now that that's out of the way, here's what I need to do with this info. I need to be able to input a city name and have it return to me all zip codes that fall under that city, as well as the zone that the city lies in. For example, if I input Chatsworth, it should give me (Zone X) and (12345, 12346, 12347) as the zip codes (just an example).
I'm not sure the best way to go about this. I could create a MySQL database and work from there, or just work from .csv files, or hardcode it into the PHP file. I don't know how to search for a value in an array column, and then return the other columns accordingly (especially with multiple zip codes per city).
If anybody can help me out, it would be greatly appreciated. Also, feel free to let me know if you need more information from me. Thanks in advance to everyone reading.
If you want to pursue the CSV approach, then the first step is reading the file into a 2D array:
$csv = array_map("str_getcsv", file("file.csv"));
Now this is an indexed array, where you need to know which column is which. But if you know the city is always in [2] then searching for the other information becomes simple:
foreach ($csv as $i=>$row) {
if ($row[2] == "Chatsworth") {
$zone = $row[0];
$zip = $row[1];
break;
}
}
Ideally you would put this into a function, so you can call it multiple times. It would be easiest if you make it configurable which column to search, and just have it return the complete found row.
Okay so if you don't know where the $city name is in, then I would propose following utility function:
function search_csv($city) {
global $csv; // pre-parsed array (can be parameter though)
foreach ($csv as $i=>$row) {
if (in_array($city, $row)) {
$result_rows[] = $row;
}
}
return $result_rows;
}
function search_zip($city) {
$rows = search_csv($city);
foreach ($rows as $i=>$row) {
$rows[$i] = end(array_filter($row, "is_numeric"));
}
return $rows;
}
The first one returns a list of $rows which match. I'll leave it up to you how to figure out which column contains which. Only for the zip code it's kind of possible to return the results deterministically.
Zone H, 92603, Irvine
Zone H, 92604, Irvine
Zone J, 92625, Corona
etc.
you can take the file and get all its contents. then split it up by new line:
$searchCity = 'Searched'; //or whatever city you are looking for
$file = file_get_contents('file.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(",",$line);
//and you know city is the 3rd element
if(trim($col[2]) == $searchCity){
$results[] = $col;
}
}
and at the end u have an array of the results like this:
$results = array(
array('Zone B', '12345', 'Searched'),
array('Zone Z', '35145', 'Searched'),
array('Zone Q', '12365', 'Searched'),
)

Music playlist via PHP. json_encode() array limit?

Im using PHP to create a playlist. Two random songs are chosen from a directory, and their name and location are stored in an array and then written to a file via json_encode().
$arraySongs[] = array('name' => $songName , 'mp3' => $webUrl);
This works great. I can make a very long playlist, two songs at a time. Id also like to remove songs, so I have an AJAX powered delete button, that posts the id of the track to be deleted, PHP then loads the whole tracklist...
$decoded = json_decode(file_get_contents($tracklist),true);
and removes the given song from the array, then re encodes and re writes the json text file. This all works great.
The problem comes whenever I try to delete anything with a playlist of more than 10 items.
Typically, my song.json file goes [{name:song1,mp3:song url},{name:song2,mp3:song2 url}]
However, when I have a list of more than 10 items, the re encoded playlist looks like this:
[{ ... },{name:song9,mp3:song9 url}],[10,{"name":song10,mp3:song10 url}]
Why is my re-encoded array get that strange [10,{"name"... [11,{"name"... [12,{"name"...
but everything below 10 is always fine?
Thanks for reading this! Any suggestions would be greatly appreciated, this is driving me nuts!
Here is the code im Using:
<?php
$json = "song.php";
$decoded = json_decode(file_get_contents($json),true);
$playlist = array();
$names = array();
// Now Get i From Javascript
$i=$_POST['id'];
//Select i's Array
$collect_array=$decoded[$i];
while (list ($key, $val) = each ($collect_array)) {
//Remove i's Values
//echo "<br />$key -> $val <br>";
unset($decoded[$i]);
}
//Take all the remaining arrays
$collect_array=$decoded;
while (list ($key, $val) = each ($collect_array)) {
$arraySongs[] = array($key , $val);
}
// Our New Array ready for json.
$jsonData = json_encode($arraySongs);
// open song.php and scribble it down
$tracklist = $json;
$fh = fopen($tracklist, 'w') or die("can't open filename: $tracklist");
fwrite($fh, $jsonData);
fclose($fh);
?>
try removing elements with unset
debug your code (not posted in the thread, so do it yourself) by adding a line where you var_dump or print_r the whole thing before json_encode
or it's a bug in json_encode which would not be nice...
Encode the track ID on 2 or even 3 digits using the php function sprintf with parameter %02d.
This worked fine for me.

how to insert value in a particular location in csv file using php

Is it possible to write at a particular location in a CSV file using PHP?
I don't want to append data at the end of the CSV file. But I want to add data at the end of a row already having values in the CSV.
thanks in advance
No, it s not possible to insert new data in the middle of a file, due to filesystem nature.
Only append at the end is possible.
So, the only solution is to make another file, write a beginning part of source, append a new value, and then append the rest of the source file. And finally rename a resulting file to original name.
There you go. Complete working code:
<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
$array2 = array_splice($array, $pos);
$array[] = $val;
$array = array_merge($array, $array2);
return $array;
}
//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;
//Full path & Name of the CSV File
$FileName = 'data.csv';
//Read the file and get is as a array of lines.
$arrLines = file($FileName);
//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);
//Convert result array to string.
$ResultStr = implode("\n", $Result);
//Write to the file.
file_put_contents($FileName, $ResultStr);
?>
Technically Col. Shrapnel's answer is absolutely right.
Your problem is that you don't want to deal with all these file operations just to change some data. I agree with you. But you're looking for the solution in a wrong level. Put this problem in a higher level. Create a model that represents an entity in your CSV database. Modify the model's state and call its save() method. The method should be responsible to write your model's state in CSV format.
Still, you can use a CSV library that abstracts low level operations for you. For instance, parsecsv-for-php allows you to target a specific cell:
$csv = new parseCSV();
$csv->sort_by = 'id';
$csv->parse('data.csv');
# "4" is the value of the "id" column of the CSV row
$csv->data[4]['firstname'] = 'John';
$csv->save();

Categories