PHP Loop though an textarea list. - php

See the code below. The polist is from a textarea field. It loops thought the array. This line produces as expected echo $line . ""; The PO Number is echoed. But the output from the query on v_devices only list the items from the last PO number in the list from the textarea.
Any ideas why? Any help would be most appreciated!!
if(isset($_POST['polist'])){
$polist=$_POST['polist'];
$text = trim($polist);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim');
foreach($textAr as $line) {
$result10 = $db->select(
"SELECT * FROM `v_devices` WHERE `ponumber` = :po",
array ("po" => $line)
);
echo $line . "<br>";
foreach($result10 as $row10) {
$poline = $line . "," . $row10['organization'] . "," . $row10['serialn'] . "," . $row10['model'];
echo $poline . "<br>";
}
}
}

The problem is that in the foreach($textAr as $line) loop you keep overwriting $result10 variable that holds the resultset of the query and you print out the results after the loop.
Either move the printing part into into this loop, or you need to add the result of the query to the $result10 variable.

Related

php multi level foreach loop remove last comma from loop

hii i have 2 level foreach loop like this and i want to remove last comma from each loop ,
/* Here is the mysql query */
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "] , ";
}
output of this program :
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
],
And i want like this
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
]
i am already use implode , trim but is remove only one loop not remove second .
sol me my problem , thanks .
You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards.
However you don't want the comma for the first output.
$addComma = ''; // should be empty for the first lines.
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo $addComma."[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "]";
$addComma = " , "; // any lines following will finish off this output
}
Rather than output the information directly you could put it in to a variable as a string. This will allow you to rtrim the last comma after the loop, then echo the information.
// Declare variable to hold the string of information.
$values = "";
/* Here is the mysql query */
foreach($loop1 as $val1)
{
$showvalone = $val1['data1'];
$values .= "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2)
{
$showvaltwo[] = $val2['data2'];
}
$values .= implode(",",$showvaltwo);
$values .= "] , ";
}
// Remove the last comma and spaces from the string.
$values = rtrim($values, ' , ');
// Output the information.
echo $values;
I have my own version in removing "," at the end and instead of adding a "."
$numbers = array(4,8,15,16,23,42);
/* defining first the "." in the last sentence instead of ",". In preparation for the foreach loop */
$last_key = end($ages);
// calling the arrays with "," for each array.
foreach ($ages as $key) :
if ($key === $last_key) {
continue; // here's the "," ends and last number deleted.
}
echo $key . ", ";
endforeach;
echo end($ages) . '.' ; // adding the "." on the last array

PHP : How to sort left to right php before reading

The code below is working in reading per row and count each identical appearances. However, I still need excel to sort per row left to right before I i save it as delimited by as text file. Right now I want to omit the excel step. I checked on php manual and saw the sort and explode functions. I inserted those command but its not working. Can someone help me point to the right direction ?
raw data is :
hero2,hero1,hero3
hero2,hero3,hero4
hero1,hero2,hero3
text file db after excel :
hero1,hero2,hero3
hero2,hero3,hero4
hero1,hero2,hero3
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
Code :
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sort ($lines);
$result = array_count_values($lines);
foreach($result as $v => $amount)
echo "Appeared " . $amount . "x: " . $v . "<br />";
?>
After reading the suggestions and samples of those who answered I came up with this code now.
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", implode($data));
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "\n";
}
?>
however the ouput became like this
output :
appeared 3x: hero2
appeared 3x: hero3
appeared 2x: hero1
appeared 1x: hero4
correct output should be like this
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
I believe your problem is you are using explode with a space and you should be using it with a comma. explode(",",$data);
I'm thinking you then also want to turn your data back into a string before you try and count them or I don't think you'll get the results you're expecting.
For example...
$sortedString = implode(",", $theArray);
You are looping over the old data before doing the sort. And you are not using a PHP function sort, you are instead making it a kind of a variable (remove the $ before it).
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($sorted_lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "<br />";
}
?>

PHP processing large form

I am having difficulty in saving all post data to csv file and emailing the values to an address. I have over 125 post variables and im quite stuck. Here is a sample of my code thus far:
<?php
$x23 = "date";
$x24 = "fclose";
$x25 = "fopen";
$x26 = "fwrite";
$x27 = "mail";
$x28 = "time";
extract($_POST);
$a1 = $_POST['fname'];
$a2 = $_POST['lname'];
$a3 = $_POST['email'];
$a4 = $_POST['landline'];
$a5 = $_POST['mobile'];
$a6 = $_POST['addr1'];
$a7 = $_POST['addr2'];
$a8 = $_POST['towncity'];
$a9 = $_POST['postcode'];
$x1d = $a1 . "," . $a2 . "," . $a3 . "," . $a4 . "," . $a4 . "," . $a5 . "," . $a6 . "," . $a7 . "," . $a8 . "," . $a9 . "
";
$quotation = $x25("file5.csv", "a");
$x26($x1d, $quotation);
$x24($x1d);
header('Location: mydomain.co');
$x20 = 'mail#mydomain.com';
$x22 = 'Quotation - My Company';
$x27($x20, $x21, $x23, $x1f);
?>
I have not put all variables in this question (not sure how to do this, but I think fputcsv() would do the job, to save all the 125 variables being written, but Iv'e never much used PHP and not sure on arrays and fputcsv()).
How would I loop through all my post variables and append them to csv as one row?
Any help would be appreciated.
The function you're looking for is implode. It implodes an array into a single string with a specific "glue", in this case ','.
So, the simplest way is to use implode(',', $_POST), but in case not all of the values are supposed to be used, there's a nice way to handle it by changing the names of the form elements.
In the form, if you change the name from "fname" into "data[fname]" and do the same for the rest of the elements, then $_POST['data'] will be an array that holds all of the values. Then using implode(',', $_POST['data']) will make sure only desired values are used.
You first of all need to be disciplined about solving one problem at a time.
(1) Create the CSV data in a variable
(2) Write the data to a file
(3) Send an email
(4) Include an attachment in the email
Or even break it down into more steps. Trying to solve a bunch of problems all at once is only going to get yourself more confused, especially if you are just getting started on programming.
So let's solve the "create the CSV" file.
You can easily loop through your $_POST and create a CSV file like this:
$csv_line = '';
$sep = ''; // don't put a comma before the 1st element
foreach ($_POST as $k -> $v) {
$csv_line .= $sep . "\"$v\"";
$sep = ','; // put a comma before the 2nd, 3rd, etc. elements
}
However, there are at least 2 problems with this. You may not want EVERY element in your $_POST to be put into the CSV, and there is no guarantee of the order those elements within $_POST.
So we'll create a separate array with just the fields we are interested in and making sure they are in the order we want to keep it:
$myFields = array('email',
'fname',
'lname',
'junk',
...);
$csv_line = '';
$sep = ''; // don't put a comma before the 1st element
foreach ($myFields as $k) {
$csv_line .= $sep . "\"$_POST[$k]\"";
$sep = ','; // put a comma before the 2nd, 3rd, etc. elements
}
Now all you have to do is write out that line into a file, figure out how to send an email, and figure out how to attach the file to the email. But at least you are one step closer...

Send tab delimited txt values to PHP array

I have a tab delimited txt file, where I would like to retrieve certain data off of each line, and place that data into an array.
Here is what I have so far:
$file_handle = fopen("/file.txt", "r");
$list = "";
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 0, "\t");
$list .= $line_of_text[10] . " - " . $line_of_text[9] . ": " . $line_of_text[6];
}
fclose($file_handle);
I then want to put $list into an array like this array($list). This array should then generate options in a select/dropdown menu on a form (the function to convert the array into options is already set, it's just a matter of getting the correct array output).
The problem is that when I access the form, all of the rows from the txt file are in one <option> in the select menu. So rather than having a select menu with a few dozen options, I'm getting a select menu with one option that contains a few dozen rows of data from the txt file.
By doing $list = "" and using string append in your while ($list .= ...) you are creating one large string. If you want an array, then create an array, and append to the array.
$file_handle = fopen("/file.txt", "r");
$list = array();
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 0, "\t");
$list[] = $line_of_text[10] . " - " . $line_of_text[9] . ": " . $line_of_text[6];
}
fclose($file_handle);

need advice with logic for coding out this php exercise

I've got a list in a text file with the top 1000 words used in the english language. Each line has a list of up to 50 words, like this:
the,stuff,is,thing,hi,bye,hello,a,stuffs
cool,free,awesome,the,pray,is,crime
etc.
I need to write code using that file as input, to make an output file with the a list of pairs of words which appear together in at least fifty different lists. For example, in the above example, THE & IS appear together twice, but every other pair appears only once.
I can't store all possible pairs of words, so no brute force.
I'm trying to learn the language and I'm stuck on this exercise of the book. Please help. Any logic, guidance or code for this would help me.
This is what I have so far. It doesn't do what's intended but I'm stuck:
Code:
//open the file
$handle = fopen("list.txt", 'r');
$count = 0;
$is = 0;
while(!feof($handle)) {
$line = fgets($handle);
$words = explode(',', $line);
echo $count . "<br /><br />";
print_r($words);
foreach ($words as $word) {
if ($word == "is") {
$is++;
}
}
echo "<br /><br />";
$count++;
}
echo "Is count: $is";
//close the file
fclose($handle);
$fp = fopen('output.txt', 'w');
fwrite($fp, "is count: " . $is);
fclose($fp);
This is what I came up with but I think it's too bloated:
plan:
check the first value of the $words array
store the value into $cur_word
store $cur_word as a key in an array ($compare) and
store the counter (line number) as the value of that key
it'll be 1 at this point
see if $cur_word is on each line and if it is then
put the value into $compare with the key as $cur_word
if array has at least 50 values then continue
else go to the next value of the $words array
if it has 50 values then
go to the next value and do the same thing
compare both lists to see how many values match
if it's at least 50 then append
the words to the output file
repeat this process with every word
There are probably 100's of solutions to this problem. Here is one
$contents = file_get_contents("list.txt");
//assuming all words are separated by a , and converting new lines to word separators as well
$all_words = explode(",", str_replace("\n", ",", $contents));
$unique_words = array();
foreach ($all_words as $word) {
$unique_words[$word] = $word;
}
this will give you all the unique words in the file in an array.
You can also use the same technique to count the words
$word_counts = array();
foreach ($all_words as $word) {
if (array_key_exists($word, $word_counts)) {
$word_counts[$word]++;
} else {
$word_counts[$word] = 1;
}
}
then you can loop through and save the results
$fp = fopen("output.txt", "w");
foreach ($word_counts as $word => $count) {
fwrite($fp, $word . " occured " . $count . " times" . PHP_EOL);
}
fclose($fp);

Categories