I'm trying to create a dropdown list which has the pre-selected value determined by a file. Unfortunately I'm not sure I'm getting the syntax right. Here's what I have so far:
<select id="SampleRate", name="SampleRate">
<?php
$controller_file = 'controllerSetup.conf';
$comment = "#";
$fp = fopen($controller_file, "r");
while (!feof($fp)) {
$line = trim(fgets($fp));
if ($line && !ereg("^$comment", $line)) {
$pieces = explode("=", $line);
$option = trim($pieces[0]);
$value = trim($pieces[1]);
$controller_values[$option] = $value;
}
}
fclose($fp);
$sampleRates = array("48", "96", "192", "350");
foreach ($sampleRates as $r) {
if ($r == $controller_values["SampleRate"]) {
echo ("<option value=$r selected>selected</option>");
} else {
echo ("<option value=$r>not selected</option>");
}
};
?>
</select>
Unfortunately, looking at the html produced in my browser, only one "not selected" option is produced. How do I get this to produce four options? I've tried replacing the "if" statement in the foreach with a simple if ($r == "48"), to no avail. Is my syntax around the echo statements correct?
Related
I managed to add multiple data in one column in the database, but now I need to display it with a new line in the browser so they don't stick with each other as I display them as an array in one column.
Here is my code:
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subArray = array("StudentAnswer");
$subId6 = $db->get("answertable", null, $subArray);
foreach ($subId6 as $sub) {
$answers[] = $sub['StudentAnswer'] . "\n";
}
foreach ($answers as $row) {
$answers2 = explode("||", $row[0]);
foreach($answers2 as $row2){
$answers3 = $row2 . '\n';
}
}
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers3);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
You are overriding $subId6 after getting its content. Try to fetch the table $rows in a new variable and the extract the content from it, like the code below.
<?php
// Example of $subId6 content
$subId6 = array(["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]], ["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]]);
// Fetch rows
foreach ($subId6 as $sub) {
$rows[] = $sub['StudentAnswer'];
}
// Decode rows
foreach($rows as $row) {
$answers = explode("\n", $row[0]);
echo "New answers: \n";
// Split answers in single answer
foreach ($answers as $answer)
echo "$answer \n";
echo "\n";
}
You will have a list of all the answers split for table rows
If you want a string of answers seperated by a space then simply do
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subId6 = $db->get("answertable");
foreach ($subId6 as $sub) {
$answers .= $sub['StudentAnswer'] . ' ';
}
$answers= rtrim($answers, ' '); //remove last space in case thats an issue later
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
I'm having a bit of an issue with converting my multidimensional array to a CSV file. The issue is that it also contains more arrays within the array.
I'm trying to convert the output of all the entries and attributes of an LDAP server into a CSV file.
A really similar question to mine can be found here: link
Essentially, I'll need the same output as the excel spreadsheet in that question, except for my fields. The issue is that not every LDAP entry has the same attributes. So some of the boxes will be empty.
So for instance I'll have
DN, ObjectClasses, Email, Phone Number, CN, UserID
cn=admin,dc=example,dc=com, top, email#gmail.com, 123-456-7890, training, 12345
But some of my arrays don't have all elements, so for instance, they are missing an email or phone number, but the rest of the elements do have the email or phone number, so I can't manually just enter all the attributes. (Also can't do this as I don't know all of the attributes that the user will need).
Here's my current output:
Amount of entries: 23dc=example,dc=com,objectclass,top,dcObject,organization,example.com,example,cn=admin,dc=example,dc=com,objectclass,simpleSecurityObject,organizationalRole,admin,"LDAP administrator",uid=newton,dc=example,dc=com,Newton,objectclass,inetOrgPerson,organizationalPerson,person,top,newton,newton#ldap.forumsys.com,"Isaac Newton",uid=einstein,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,"Albert Einstein",Einstein,einstein,einstein#ldap.forumsys.com,314-159-2653,uid=tesla,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,posixAccount,"Nikola Tesla",Tesla,tesla,tesla#ldap.forumsys.com,88888,99999,home,uid=galieleo,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,"Galileo Galilei",Galilei,galieleo,galieleo#ldap.forumsys.com,uid=euler,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,euler,Euler,"Leonhard Euler",euler#ldap.forumsys.com
Basically, it's just completely unorganized (don't mind the amount of entries: 23 part)
I was wondering how I could organize all my outputs?
Here's my current code:
<?php
session_start();
$ldaprdn = 'cn=read-only-admin,dc=example,dc=com';
$ldappass = 'password';
$ldapuri = "ldap.forumsys.com";
// Connecting to LDAP
$ldapconn = ldap_connect($ldapuri)
or die("That LDAP-URI was not parseable");
//We need to set the LDAP Protocol Version or else it isn't able to bind properly to the LDAP server.
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
//We bind to the LDAP server using the previous credentials and location.
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
//Gives where to search & what to search for
$dn = "dc=example,dc=com";
$filter = "(objectclass=*)";
//Saves the result into result variable
$result = ldap_search($ldapconn, $dn, $filter);
$info = ldap_get_entries($ldapconn, $result);
//Saves all the attributes of all entries into an array.
function cleanUpEntry( $entry ) {
$retEntry = array();
for ( $i = 0; $i < $entry["count"]; $i++ ) {
if (is_array($entry[$i])) {
$subtree = $entry[$i];
//This condition should be superfluous so just take the recursive call
//adapted to your situation in order to increase perf.
if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
$retEntry[$subtree['dn']] = cleanUpEntry($subtree);
}
else {
$retEntry[] = cleanUpEntry($subtree);
}
}
else {
$attribute = $entry[$i];
if ( $entry[$attribute]['count'] == 1 ) {
$retEntry[$attribute] = $entry[$attribute][0];
} else {
for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
$retEntry[$attribute][] = $entry[$attribute][$j];
}
}
}
}
return $retEntry;
}
echo "Amount of entries: ".(sizeof(cleanUpEntry($info)));
/*
//Prints all the elements in the array
echo "<pre>";
print_r(cleanUpEntry($info));
echo "</pre>";*/
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$arrayList=array_flatten($value);
foreach ($arrayList as $listItem) {
$result[] = $listItem;
}
}
else {
$result[$key] = $value;
}
}
return $result;
}
function arrayToValues(array $data)
{
$output = array();
foreach ($data as $key => $item) {
if (is_array($item)) {
$output = array_merge($output, array($key), arrayToValues($item));
} else {
$output[] = $item;
}
}
return $output;
}
$csvData = implode(',', arrayToValues(cleanUpEntry($info)));
$csvExport = explode(',', $csvData);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="export.csv";');
$f = fopen('php://output', 'w');
fputcsv($f, arrayToValues($csvExport));
?>
I have a document called subjects.txt in the following format:
DateCreated,Subject,Link
18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address.html
18.10.2015,"English",http: //address.html
19.10.2015,"Science",http: //address.html
17.10.2015,"Math",http: //address.html
The file contains URLs of sites created based on a school subject. There can be more than one site for a subject.
The goal is to use PHP to open, read, and display the contents of the file in the following format:
Math
Link 1
Link 2
English
Link 1
Link 2
Science (because there's only one link, the name of the subject is the
link)
So far I've been able to open and read the file:
$file = "./subjects.txt";
$subjects = file_get_contents($file);
I'm having trouble trying to determine how to go about writing the file in specified format.
I've tried using explode to separate the elements with "," - however I don't know where to go from there.
Your input file looks to be in Comma-separated values (CSV) format. PHP has a built-in fgetcsv function designed to make reading CSV data from a file easy.
<?php
$file = './subjects.txt';
$fh = fopen($file, 'r');
if ($fh === false) {
die("Can not read {$file}");
}
$data = array();
while (($row = fgetcsv($fh, 1000, ',')) !== false) {
if ($row[0] === 'DateCreated') {
// Ignore the column header row
continue;
}
list($date, $subject, $link) = $row;
if (!isset($data[$subject])) {
$data[$subject] = array();
}
$data[$subject][] = $link;
}
fclose($fh);
foreach ($data as $subject => $links) {
// TODO: output each subject here
}
Here is another version
<?php
$file = "./subjects.txt";
$h = fopen($file, "r");
if($h !== false) {
$subjects = [];
$data = [];
while(!feof($h)) {
if($line = trim(fgets($h))) {
$line = explode(",", $line);
if(!in_array("DateCreated",$line)) {
array_push($subjects, $line);
}
}
}
fclose($h);
foreach ($subjects as $subject) {
if(!isset($data[$subject[1]])) {
$data[$subject[1]] = [];
}
$data[$subject[1]][] = $subject[2];
}
foreach ($data as $subject => $links) {
if(count($links) == 1) {
echo "<p>$subject</p>\n";
} else {
$i = 1;
echo "<p>$subject</p>\n";
echo "<ul>\n";
foreach ($links as $link) {
echo "<li>link$i</li>\n";
$i++;
}
echo "</ul>\n";
}
}
}
?>
The problem using file_get_contents() is that retrieves all the file contents into $subjects.
You have to use a different approach. For example fgets():
$fp = fopen("./subjects.txt", "r");
if ($fp){
while (($line = fgets($fp)) !== false){
// So here you can treat each line individually.
// You can use explode (";", $line) for example if the line is not empty
}
}
fclose($fp);
Using fgets() will allow you to parse each of the file's lines individually.
As stated doing this with a database would be much easier probably 3 lines of code. Here's one approach you could use though.
$data = '18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address1.html
18.10.2015,"English",http: //address2.html
19.10.2015,"Science",http: //address3.html
17.10.2015,"Math",http: //address4.html';
preg_match_all('~^(.*?),"(.*?)",(.*?)$~m', $data, $fields);
array_multisort($fields[2], SORT_STRING, $fields[1], $fields[3]);
$lastcat = '';
foreach($fields[2] as $key => $cat) {
if($cat != $lastcat) {
echo $cat . "\n";
}
$lastcat = $cat;
echo $fields[3][$key] . "\n";
}
Output:
English
http: //address1.html
http: //address2.html
Math
http: //address4.html
http: //address.html
Science
http: //address3.html
The array_multisort is how the categories are grouped.
Here's a regex101 demo of what that regex is doing. https://regex101.com/r/wN3nB2/1
Update for single record check (only ran 1 test on it):
$data = '18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address1.html
18.10.2015,"English",http: //address2.html
19.10.2015,"Science",http: //address3.html
17.10.2015,"Math",http: //address4.html';
preg_match_all('~^(.*?),"(.*?)",(.*?)$~m', $data, $fields);
array_multisort($fields[2], SORT_STRING, $fields[1], $fields[3]);
$lastcat = '';
foreach($fields[2] as $key => $cat) {
if((empty($fields[2][($key +1)]) && $cat != $lastcat)|| ($cat != $lastcat && !empty($fields[2][($key +1)]) && $fields[2][($key +1)] != $cat)) {
//single record
echo $cat . $fields[3][$key] . "\n";
} else {
if($cat != $lastcat) {
echo $cat . "\n";
}
$lastcat = $cat;
echo $fields[3][$key] . "\n";
}
}
<?php
{
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
?>
I get the same 20 results every time, and I have used pagination as you can see in my code. Every time I print the next page token I get a different one.
I would really appreciate if someone could point out the error in my code because I am stuck with this for quite some time. You are also most welcome to give any kind of relevant suggestion.
use pagetoken instead of nextpage in your url string and in the last two calls give only api key and page token as parameter and after each api call use sleep(2) i tried your code and it works perfectly when the following changes are made.happy coding!
<?php
//echo"hello";
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL ="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=26.177194999999998,91.77591333333334&radius=3000&types=mosque&key=your APIkey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
foreach( $dataArray->results as $details) {
//echo $details->place_id;
array_push($references, $details->place_id);
}
foreach($references as $reference)
{
$count=$count+1;
//echo $count." ";
$placeSearchURL="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$reference."&key=your apikey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
echo $dataArray->result->name."<br>";
echo "lat ".$dataArray->result->geometry->location->lat."<br>";
echo "lon ".$dataArray->result->geometry->location->lng."<br>";
echo "address ".$dataArray->result->formatted_address."<br>";
echo "<br>";
}
?>
basically i wanted to find a way to get more than 20 places of type masjid so i first used radar search to get placeids and then for each placed_id got the information and best part is you can get arount 200 results of nearby places
I have this piece of code
foreach($mnthArrPtrn as $m => $mn)
{
if(!isset($catName)) {
$catVals = array();
$prevCat = $catName = $pntChrtQry[0]['CAT']['categoryname'];
$pntVals .= '{name:'.$catName.',data:[';
}else if($prevCat != $catName) {
$prevCat = $catName;
$catVals = array();
$pntVals .= '{name:'.$catName.',data:[';
}
foreach($pntChrtQry as $key => $val){
$catName = $val['CAT']['categoryname'];
if($prevCat != $catName){
continue 2;
}
echo '<br />$m::'.$m;
echo '<br />$mn::'.$mn;
echo '<br />$val::'.$val[0]['MNTH'];
if($m == $val[0]['MNTH'] || $mn == $val[0]['MNTH']){
$catVals[] = $val[0]['total'];
}
}
pr($catVals);
if(!isset($catName)){
$pntVals .= ']},';
}
$catName = $val['CAT']['categoryname'];
}
1st loop iterates over a months array which are joined as a key value pair.
What I am doing here is on getting a new catName I continue the internal loop but at the same time I want to restart loop 1 with $prevCat,$catName still preserving their values.
Is this possible? Sorry If this is a silly question.
I tried converting the first one to a while statement and use a reset then but It didn't help me.
Something like this will allow you to arbitrarily restart a loop:
while (list($key, $value) = each($mnthArrPtrn)) {
if ($needToRestart) {
reset($mnthArrPtrn);
}
}
See more here.