How do you retrieve an array based on user input? - php

This is the data in the text file contain the data
I have already store the data in the array
enter image description here
<?php
if (!(isset($_GET['job_title']) && empty($_GET['job_title']))) {
$job_title = $_GET['job_title'];
echo $job_title;
$filename = __DIR__ . '/jobpost.txt';
if (file_exists($filename)) {
$data= null;
$allData = array();
$handle = fopen($filename, "r");
while (!feof($handle)) {
$onedata = fgets($handle);
if ($onedata != "") {
$data = explode("\t", $onedata);
$allData[] = $data;
}
}
echo "<pre>";
print_r($allData);
echo "</pre>";
} else {
echo "file does not exist";
}
} else {
echo "<p class=\"bg_danger\"> must enter the job title </p>";
}
?>
My question is when user enter an input "software engineering" and based on the input value, must retrieve the related the array.

First don't forget to filter/sanitize your user inputs.
Now Check while storing data into the array if you can create a array with keys as "software engineering"
if that's not possible you can loop through array once & create array you need
$arrNewDataArray = [];
foreach( $dataArray as $arr ){
$arrNewDataArray[$arr[1]] = $arr;
}
Then you will be able to check if user input value is present in the array & retrieve it like below.
$userinput = 'software engineering';
$arrayYouNeed = [];
if( isset( $arrNewDataArray[$userinput] ) ) {
$arrayYouNeed = $arrNewDataArray[$userinput];
}

Related

How to output multi-dimensional array to CSV file in PHP?

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

create multiple arrays from csv file using PHP

I have csv file with 1500+ entries in a column.I can able to read csv file's all values of column with this.
$rowcount = 1;
$srcFileName = "input/test.csv";
$file = fopen($srcFileName,"r");
$inputfielscount = count(file($srcFileName, FILE_SKIP_EMPTY_LINES));
while($rowcount < $inputfielscount)
{
$row = fgetcsv($file);
$result=array("id" =>$row[0],"des"=>"I am jhon",salery="10000");
$Final=array("listingsEmp"=>$result);
}
After reading first (1-10) value i will create an array (like array [0] =>$result) and Then wantto repeat same task from (11-20) and create another array (like array [1] =>$Final this time $final array contain information about the next ids whic we read from csv file (11-10)) and so on.
For the above requirment i changed code to this :
$rowcount = 1;
$srcFileName = "input/test.csv";
$file = fopen($srcFileName,"r");
while($rowcount < 20)
{
if(($rowcount % 10 == 0) && ( $rowcount != 0)) {
$rowcount++;
break;
}else{
$row = fgetcsv($file);
// some curl code for fetching data according to csv file field(Id)
$result=array("id" =>$row[0],"des"=>"I am jhon",salery="10000"); //contain 10 array
}
}
$Final=array("listingsEmp"=>$result);
Now i will post this $final array which has (0-10 index array ,each has unique id and corresponding values) using curl and get response which i am save in csv file.
$currenttime=date("Y-m-d-H_i_s");
$opfile='output'.$currenttime.'.csv'; //path wher op csv file exist
if(!#copy($srcFileName,'/output/'.$opfile))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}else { // echo "File copied from remote!";
$fp = fopen('output/output'.$currenttime.'.csv',"a");
$fr = fopen($srcFileName,"r");
$rowcounts=0;
$FinalRES=$Final->response;
while($rowcounts< $inputfielscount) {
$resultBulk=$FinalRES[$rowcounts];
$resultBulkStatus=$FinalRES->status;
$resultBulkErrors=$FinalRES->errors;
$errorMsgArray=$resultBulkErrors[0];
$BulkErrorsMessage=$errorMsgArray->message;
$rows = fgetcsv($fr);
if($resultBulkStatus=='failure'){
$list = array ($rows[0],$rows[1],$resultBulkStatus,$BulkErrorsMessage);
}else {
$list = array ($rows[0],$rows[1],$resultBulkStatus,"successfully");
}
fputcsv($fp,$list);
//$p++;
$rowcounts++;
}
}
This full code runs once and give response for 10 ids ,i want repeat this code again for next 10 id (11-20)and then for (21-30) so on .
Once all response write in output csv file After that it display download output file link,Output file contain full response for all Ids which is in csv file(1500 +)
<?php $dnldfilw='output'.$currenttime.'.csv';?>
<a href='download.php?filename=<?php echo $dnldfilw; ?>'>Download Output file</a>
?>
The easiest method is to just use the file() function you are already using...
So to shorten the code to some pseudocode:
<?php
$indexedArray = array();
$indexedSplit = 10;
$lines = file($srcFileName);
$tempArray = array();
foreach($lines as $line) {
if(count($tempArray) % $indexedSplit === 0) {
$indexedArray[] = $tempArray;
$tempArray = array();
}
$tempArray[] = $line;
}
foreach($indexedArray as $index => $valueArray) {
// do the curl magic
// write results of curl into csv
}
Your question is poorly phrased, but I think this would be your aim, right?

Decode the array values

I want to decode array values for passing it into json. I want to pass the values in contentvalue baaed on content type into json. Now It shows null. I want to move array value as $zip_num=$content->zip; based on content type.
while ($ee = mysql_fetch_array($query)) {
$key_val = $ee['CONTENT_TYPE'];
$content = json_decode($ee['CONTENT_VALUE']);
if ($key_val == 'stat_sum') {
$stat = $content;
}
if ($key_val == 'zip_stats') {
$zip[] = $content;
$zip_num=$content->zip;
$zip_cou=$content->count;
}
if ($key_val == 'qual_stats') {
$qual[] = $content;
}
}
$new = array('ID'=>$id,'zip'=>$zip_num);
echo $json = json_encode($new);
}
Replace $key_val (that one which is in if statement) with $ee['CONTENT_TYPE']

How to store string in an array? - PHP

I'm trying to store a string in an array, but it doesn't save the array:
<?php
session_start();
$username = $_POST["username"];
$password = $_POST["password"];
$users = array();
$passes = array();
/*if (isset($_SESSION['users'])) {
$users = unserialize($_SESSION['users']);
}
if (isset($_SESSION['passes'])) {
$passes = unserialize($_SESSION['passes']);
}*/
if (isset($_POST['button'])) {
$login_successful = false;
for ($i = 0; $i < count($_SESSION['user']); $i++) {
if ($username === $_SESSION['user'][$i] && $password === $_SESSION['pass'][$i]) {
echo "<p style=\"font-family: Open Sans\">Logged in as " .$users[$i] ."</p>";
$login_successful = true;
break; // no need to continue the loop here, so we break out of it
}
}
if (!$login_successful) {
echo "<p style=\"font-family: Open Sans\">Login Failed</p>";
}
}
else if (isset($_POST['register'])) {
$users = array_push($users, $username);
$passes = array_push($passes, $password);
$_SESSION['user'] = serialize($users);
$_SESSION['pass'] = serialize($passes);
echo "Made your account successfully! Go back to login";
}
else if (isset($_POST['userlist'])) {
$users = unserialize($_SESSION['users']);
$passes = unserialize($_SESSION['passes']);
for ($i = 0; $i < count($users); $i++) {
echo $user[$i];
echo $passes[$i];
}
}
?>
It doesn't save the array, it changes it only for the current page it was called on and then the array goes back to nothing.
Thanks in advance
You seem to have a huge misunderstanding of how PHP works. Each time a php script runs, it's like the first very first time it has ever ran. So, your array will be removed from memory when the script finishes.
However, if you want to carry data between requests, you can try a session.
session_start();//important
//YOUR EXISTING ARRAY
$array = array("element", "element 2", "element 3");
//ADD YOUR NEW ELEMENT TO THE ARRAY
$array = array_push( $array, "NEW ELEMENT" );
//store the new serialized (converted to string) array
$_SESSION['my_array'] = serialize( $array );
if ( isset($_SESSION['my_array']) ) {
//grab the serialized (string version) of the array, and convert it back to an array
$my_array = unserialize( $_SESSION['my_array'] ); //holds [0] => "el1", [1] => "el2"
}
Read more about sessions from the PHP manual.
You can also try cookies or storing the array into a database. Just know that cookies are stored on the user's computer, and sessions are stored on the server.
you can use array_push like this : $user=array_push($user,$username);
That's all!
let's do some improvement on Ryan Smith's solution to make it simpler
session_start();
$_SESSION['users'][] = 'Hello';
var_dump($_SESSION['users']);
// if you wanna use $users,
/*
if(isset($_SESSION['users'])) {
$users = unserialize($_SESSION['users']);
}
*/

Encoding JSON with double quotes instead of single quotes

I have a json.php file which delivers results like this:
{ "markers": [ {'a1_id':"4213CK58", etc.
The problem is that the Google Maps API doesn't like single quotes and so I need my results like this:
{ "markers": [ {"a1_id":"4213CK58", etc.
Replacing ' by " in the code doesn't deliver...
<?php
// Iterate over the rows
$nextRow= $result->nextRow();
$r = 1;
$info = array();
while ( $nextRow ) {
$nextColumn = $result->nextColumn();
// Has this column been printed already
if ( $unique )
{
$d = $result->getDataForField($unique);
if ( array_key_exists($d, $already) )
{
$nextRow= $result->nextRow();
continue;
}
$already[$d] = true;
}
echo '{';
// Iterate over the columns in each row
while ( $nextColumn )
{
// Get the variable
$variable = $result->getOutputVariable();
$name = $variable->getName(true);
$data = $result->getDataForField();
if ( !isset($info[$name]) ) {
$info[$name]['translate'] = $variable->shouldTranslate();
$info[$name]['type'] = $variable->getDataType();
$info[$name]['linkable'] = $variable->isLinkable();
}
// Translate the data if requested
if ( $info[$name]['translate'] ) {
$data = LQMTemplate::_($data);
}
$data = $variable->format($data, false);
$type = $info[$name]['type'];
if ( ($type == 'bool') or ($type == 'boolean') )
{
$data = $data ? '1' : '0';
echo "'$name':$data";
} elseif ( $encode ) {
// Can we use json_encode ?
// str_replace because some versions of PHP have a bug that will over escape forward slashes
echo "'$name':".str_replace('\\/', '/', json_encode($data));
} else {
$data = LQMUtility::jsonEscape($data, '"');
echo "'$name':\"$data\"";
}
// Conditionally print the next column
$nextColumn = $result->nextColumn();
if ( $nextColumn ) echo ",\n ";
}
// Conditionally print the next column
$nextRow = $result->nextRow();
echo $nextRow ? "},\n" : "}\n";
$r++;
}
unset($result);
echo ']}';
}
}
Create an array containing the data you want to encode and then use PHP's builtin json_encode() function.

Categories