I am working on a simple API for a web server where you can set answers to querys with multiple querys tied to one answer.
Here is my code so far but I need a way to append queries (multikeys) to each question (value) and I'm not sure how to fit it together.
$question = urldecode($_GET["q"]);
$admin = urldecode($_GET["admin"]);
$answer = urldecode($_GET["answer"]);
$donext = urldecode($_GET["donext"]);
if ($admin == "password123") {
$file = fopen("program.json", "a+") or die ("file not found");
$json = file_get_contents('program.json');
$data = json_decode($json, true);
$keys = array($q1, $q2, $q3); // need to append this with $q each time.
$train = array_fill_keys($keys, '$a."+".$donext');
//$data[$tagid] = $tagvalue;
$newjson = json_encode($data);
file_put_contents('program.json', $newjson);
fclose($file);
} else {
$file = fopen("program.json", "a+") or die ("file not found");
$json = file_get_contents('program.json');
$data = json_decode($json, true);
$a = $data->$q;
$piece = explode('+', $a);
$reply = $piece[0];
$nextcontext = $piece[1];
fclose($file);
echo $reply;
echo $donext;
}
How to put multiple keys to the same value:
<?php
$questionkeys = array('hi','hey','yo');
$answervalue = "hello to you too";
$outputarray = array_fill_keys($questionkeys, $answervalue);
echo $outputarray;
?>
Related
I have 2 array in my code, like the shown below:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
for($i=0;$i<$count;$i++){
for($j=0; $j<1; $j++){
$stopword[$i] = $stoplist[$i][$j];
}
}
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
var_dump($hasilfilter);
?>
$stopword contain of some stop word like attached in http://xpo6.com/list-of-english-stop-words/
All I wanna do is: I want to check if save the element that exist in array $kata and it is not exist in array $stopword
So I want to delete all the element that exist in both array $kata and $stopword .
I read some suggestion to use array_diff , but somehow it doesn't work to me. Really need your help :( Thanks.
array_diff is what you need, you are right. Here is a simplified version of what you try to do:
<?php
// Your string $kalimat as an array of words, this already works in your example.
$kata = ['I', 'just', 'want', 'to', '...'];
// I can't test $stopword code, because I don't have your file.
// So let's say it's a array with the word 'just'
$stopword = ['just'];
// array_diff gives you what you want
var_dump(array_diff($kata,$stopword));
// It will display your array minus "just": ['I', 'want', 'to', '...']
You should also double check the value of $stopword, I can't test this part (don't have your file). If it does not work for you, I guess the problem is with this variable ($stopword)
There is a problem in your $stopword array. var_dump it to see the issue.array_diff is working correct.
Try following code I wrote to make your $stopword array right:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
$stopword= call_user_func_array('array_merge', $stoplist);
$new = array();
foreach($stopword as $st){
$new[] = explode(' ', $st);
}
$new2= call_user_func_array('array_merge', $new);
foreach($new2 as &$n){
$n = trim($n);
}
$new3 = array_unique($new2);
unset($stopword,$new,$new2);
$stopword = $new3;
unset($new3);
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
print "<pre>";
var_dump($hasilfilter);
print "</pre>";
?>
I hope it helps
Good day!
I am trying to print the array on the text file but whenever I try to run my code, I would always get this error
Notice: Array to string conversion in <path>
It would point to this line of code:
fwrite($listonedupe, $result1.PHP_EOL);
What could be the possible solution for this?
<?php
$getapps = 'B:\z.test\runningapps.txt';
$fordupe = 'B:\z.test\fordupe.txt';
$sendtoserver = 'B:\z.test\sendtoserver.txt';
if ($file1 = fopen($getapps, "r"))
{
$read1 = fread($file1,filesize($getapps));
$line1 = explode("\n", $read1);
$file2 = fopen($fordupe, "r");
$read2 = fread($file2,filesize($fordupe));
$line2 = explode("\n", $read2);
$result1 = array_diff($line1, $line2);
if (count($result1)>0)
{
$forserver = fopen($sendtoserver,"w");
foreach ($result1 as $value1) {
fwrite($forserver, $value1.PHP_EOL);
// for checking server
$s1 = fopen($sendtoserver, "r");
$s2 = fread($s1,filesize($sendtoserver));
$s3 = explode("\n", $s2);
var_dump($s3);
$listonedupe = fopen($fordupe,"a");
fwrite($listonedupe, $result1.PHP_EOL);
}
// for checking dupe
var_dump($line2);
}
else
echo "ok";
}else
die("Unable to open file!");
?>
Replace fwrite($listonedupe, $result1.PHP_EOL); to fwrite($listonedupe, $value1.PHP_EOL);
I am trying to parse a JSON file for the first time ever and insert the information into my database. The problem is that this object/array is multidimensional, so $number = stats[0] is getting values on each level of the array. This is a link to the JSON file. I want to avoid everthing but the data: values that I exploded with PHP. Here is a link to my output right now. If you look at my output, I am only interested in the 8,C,J. Pavelski and 26. Those are the values I want in my database.
$json = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json");
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$stats = explode(",", $val);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];
echo $number." ".$position." ".$name." ".$points."<br />";
/* $query = "INSERT INTO stats2015_2016 ('number','position','name','gp','goals','assists','points','plsmns','pim','shots', 'toi', 'pp', 'sh', 'gwg', 'ot')
VALUES ('$number','$position','$name','$gp','$goals','$assists','$points','$plsmns','$pim','$shots','$toi','$pp','$sh','$gwg','$ot')";
$result= $db->query($query); */
}
Thank you
$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');
$json = json_decode($json, TRUE);
$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];
foreach($skaterData as $d){
$sk = explode(',', $d['data']);
$number = $sk[0];
$position = $sk[1];
$name = $sk[2];
$points = $sk[6];
echo $number." ".$position." ".$name." ".$points."<br />";
}
repeat for goalie data as required
I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;
Ive the following Code , a function take a list of usernames and put in them in array then execute function called function get_all_friends , Code works fine and no error , my question here how to adjust the code if ive bulk of usernames lets say like 10k ?
Like reading from file include all usernames name and put them in array using
$file_handle = fopen("users.txt")
please advise !
<?PHP
$user1 = "usernamehere";
$user2 = "usernamehere";
$user3 = "usernamehere";
$u[] = $user1;
$u[] = $user2;
$u[] = $user3;
function get_all_friends($users)
{
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$list = array();
foreach($users as $user)
{
$result = $connection->get( 'friends/ids', array(
"screen_name"=> $user)
);
foreach($result->ids as $friend)
{
$list[] = $friend;
}
}
return $list;
}
//call the function
$result = get_all_friends($u);
foreach($result as $res)
{
$query = "INSERT INTO friends (userid, name, grade, flag) VALUES ($res, 'name', 100, 0 ) ";
mysql_query($query);
}
//to print the databse result
echo "row<br />";
$res = mysql_query("SELECT * FROM friends");
while ($row = mysql_fetch_assoc($res))
{
print_r($row);
}
?>
Something like the following should work (untested):
$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
$usernames = preg_split("/ (,|\\n) /", $contents);
fclose($file_handle);
The usernames must be separated by a comma or a new line.
Although, if you are positive that the usernames will only be separated by a new line OR a comma, this code will be faster:
$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
// new line:
$usernames = explode("\n", $contents);
// or comma:
$usernames = explode(",", $contents);
fclose($handle);
Please choose only one of the $usernames definitions.
Specifically to answer the question, check file(..) - "Reads entire file into an array"
http://php.net/manual/en/function.file.php
Although you probably don't want to be doing it this way, if the file is large you'll be much better off reading sequentially or doing some sort of direct import.