Hi guys I have been trying to do this for sometime. Would you please give me an insight on how to go about this.
I have a text file containing questions and their respective multiple choice answer spaced using space bar between each element.
I have been able to read and put the text file lines into arrays. But now what has prooved difficult to achieve is how to put each and every element to an html form element. these are my codes:
Text file:
Number Question (a) (b) (c) (d)
1 The most important feature of spiral model is requirement analysis. risk management. quality management. configuration management.
2 The worst type of coupling is Data coupling. control coupling. stamp coupling. content coupling.
3 One of the fault base testing techniques is unit testing. beta testing. Stress testing. mutation testing.
4 A fault simulation testing technique is Mutation testing Stress testing Black box testing White box testing
5 RS is also known as specification of White box testing Stress testing Integrated testing Black box testing
The page that reads the text file:
`html>
<head>
<title>read</title>
</head>
<body>
<b><u> QUESTIONS AND ANSWERS QUIZ</u></b <br />
<p>
<?php
$openFile = fopen("questionandanswers.txt", "r") or exit ("unable to open the text file");
$fileContents = fread($openFile, filesize("questionandanswers.txt"));
fclose($openFile);
$delimiter = " ";
$myArray = explode($delimiter, $fileContents);
print_r($myArray);
?>
</p>
</body>
</html>`
THe print_r displays the following:
Array ( [0] => Number [1] => Question [2] => (a) [3] => (b) [4] => (c) [5] => (d) 1 [6] => The most important feature of spiral model is requirement analysis. [7] => risk management. [8] => quality management. [9] => configuration management. 2 [10] => The worst type of coupling is [11] => Data coupling. [12] => control coupling. [13] => stamp coupling. [14] => content coupling. 3 [15] => One of the fault base testing techniques is [16] => unit testing. [17] => beta testing. [18] => Stress testing. [19] => mutation testing. 4 [20] => A fault simulation testing technique is [21] => Mutation testing [22] => Stress testing [23] => Black box testing [24] => White box testing 5 [25] => RS is also known as specification of [26] => White box testing [27] => Stress testing [28] => Integrated testing [29] => Black box testing )
You explode() using space as separator, that's why you are getting each word as an array element. explode() just uses the character you give it and split the string whenever it encounters the character.
Your data (the file) hasn't got a pattern. So you need to stablish some rules in the text, or you won't be able to separate the information you want:
I modified your text stablishing some rules:
The questions will be finished with a colon(:).
The answers will be finished with a dot(.), all of them but the last one, as we will use the number of the question as separator.
The questions or answers won't contain any numbers [0-9] or it will confuse the regex.
This is the resulting text I modified manually to make the text work:
$string = 'Number Question (a) (b) (c) (d) 1 The most important feature of spiral model is: requirement analysis. risk management. quality management. configuration management 2 The worst type of coupling is: Data coupling. control coupling. stamp coupling. content coupling 3 One of the fault base testing techniques is: unit testing. beta testing. Stress testing. mutation testing 4 A fault simulation testing technique is: Mutation testing. Stress testing. Black box testing. White box testing 5 RS is also known as: specification of White box testing. Stress testing. Integrated testing. Black box testing';
The solution:
After that we can use some code to separate the information:
<html>
<head>
<title>read</title>
</head>
<body>
<b><u> QUESTIONS AND ANSWERS QUIZ</u></b> <br />
<?php
$openFile = fopen("questionandanswers.txt", "r") or exit ("unable to open the text file");
$string = fread($openFile, filesize("questionandanswers.txt"));
//Regex to get from the first number to the string's end, so we ignore the Number Question... bit;
preg_match('/\d.*/', $string, $match);
//We get all the strings starting with a number until it finds another number (which will be the beginning of another question;
preg_match_all('/\d\D*/', $match[0], $results);
$qas = array(); // We prepare an array with all the questions/answers
foreach($results[0] as $result){
//Separating the answer from the string with all the answers.
list($question, $all_answers) = explode(':', $result);
//Separating the different answers
$answers_array = explode('.', $all_answers);
//Stuffing the question and the array with all the answers into the previously prepared array;
$qas[] = array('question' => $question, 'answers' => $answers_array);
}
//Looping through the array and outputting all the info into a form;
foreach($qas as $k => $v){
echo "<label>{$v['question']}</label><br/>";
echo "<select>";
//we loop through $v['answers'] because its an array within the array with all the answers.
foreach($v['answers'] as $answer){
echo "<option>$answer</option>";//the output
}
echo "</select>";
echo "<br/><br/>";
}
?>
</body>
</html>
Looks complex because of all the comments, they are less than 20 lines of text actually
You can see the output here: output
Notes
Did this just to practice, but next time try to research more, and ask specific questions, or people will ignore/downvote your, have a good read about the Stackoverflow's FAQs
You should format your array into a multidimensional one, where the index 0 is the question:
Array
(
[0] = array
(
[0] = "This is the first question";
[1] = "Answer A";
[2] = "Answer B";
)
[1] = array
(
[0] = "This is the second question";
[1] = "Answer A";
[2] = "Answer B";
[3] = "Answer C";
)
)
You can now include it the following way:
<form>
<?php
foreach($filecontent as $question)
{
echo '<p>' .$question[0] .'</p>';
for($i = 1; $i < count($question); $i++)
{
echo '<input value="' .$question[$i] .'" />';
}
}
?>
</form>
Related
I'm wanting to replace the first character of a string with a specific character depending on its value,
A = 0
B = 1
C = 2
Is there a way to do this based on rules? In total I will have 8 rules.
Ok, so I'm editing this to add more information as I don't think some people understand / want to help without the full picture...
My string will be any length between 5 and 10 characters
Capitals will not factor into this, it is not case sensitive
Currently there is no code, I'm not sure the best way to do this. I can write an if statement on a substring, but I know straight away that is inefficient.
Below is the before and after that I am expecting, I have kept these examples simple but all I am looking to do is replace the first character with a specific character depending on its value. For now, there are eight rules, but this could grow in the future
INPUT OUTPUT
ANDREW 1NDREW
BRIAN 2RIAN
BOBBY 2OBBY
CRAIG 3RAIG
DAVID 4AVID
DUNCAN 4UNCAN
EDDIE 5DDIE
FRANK 6RANK
GEOFF 7EOFF
GIANA 7IANA
HAYLEY 8AYLEY
So as you can see, pretty straight forward, but is there a simple way to specifically specify what a character should be replaced by?
Assuming all the rules are for single characters, like in the example, it would be easisest to code them in to a dictionary:
$rules = array('A' => 0, 'B' => 0 /* etc... */);
$str[0] = $rules[$str[0]];
I think this is what you want.
<?php
$input = array('ANDREW','BRIAN','BOBBY','CRAIG','DAVID','DUNCAN','EDDIE','FRANK','GEOFF','GIANA','HAYLEY');
$array = range('A','Z');
$array = array_flip(array_filter(array_merge(array(0), $array)));
$output = [];
foreach($input as $k=>$v){
$output[] = $array[$v[0]].substr($v, 1);
}
print_r($output);
?>
Output:
Array (
[0] => 1NDREW
[1] => 2RIAN
[2] => 2OBBY
[3] => 3RAIG
[4] => 4AVID
[5] => 4UNCAN
[6] => 5DDIE
[7] => 6RANK
[8] => 7EOFF
[9] => 7IANA
[10] => 8AYLEY
)
DEMO: https://3v4l.org/BHLPk
I have an array that outputs the following:
Array
(
[0] => #EXTM3U
[1] => #EXTINF:206,"Weird" Al Yankovic - Dare to be Stupid
[2] => E:\Dare to be Stupid.mp3
[3] => #EXTINF:156,1910 Fruitgum Company - Chewy, Chewy
[4] => E:\Chewy Chewy.mp3
[5] => #EXTINF:134,1910 Fruitgum Company - Goody Goody Gumdrops
[6] => E:\Goody Goody Gumdrops.mp3
[7] => #EXTINF:134,1910 Fruitgum Company - Simon Says
[8] => E:\Simon Says.mp3
[9] => #EXTINF:255,3 Doors Down - When I'm Gone
[10] => E:\When I'm Gone.mp3 [
11] => #EXTINF:179,? And the Mysterians - 96 Tears**
)
I need to split this array then loop through and save each value to the database, e.g:
"Weird" Al Yankovic - Dare to be Stupid
Fruitgum Company - Chewy, Chewy
Save each value above to database individually.
Thanks in advance!
Edit: Added from the comments
Let me try and explain in more detail. I start with a string that looks like this:
#EXTM3U #EXTINF:266,10cc - Dreadlock Holiday
D:\Music - Sorted\Various Artists\De Beste Pop Klassiekers Disc 1\10cc - Dreadlock Holiday.mp3
#EXTINF:263,1919 - Cry Wolf
D:\Music - Sorted\Various Artists\Gothic Rock, Vol. 3 Disc 2\1919 - Cry Wolf.mp3
#EXTINF:318,3 Doors Down - [Untitled Hidden Track]
D:\Music - Sorted\3 Doors Down\Away From The Sun\3 Doors Down - [Untitled Hidden Track].mp3
I'm then trying to strip everything out of this and just have an array of track titles, this is a playlist file for online radio. What I am doing so far:
$finaloutput = $_POST['thestring'];
$finaloutput = str_replace('#EXTINF:','',$finaloutput);
$finaloutput = str_replace('#EXTM3U','',$finaloutput);
$finaloutput = preg_split("/\r\n|\r|\n/", $finaloutput);
foreach ($finaloutput as $value) {
echo $value; echo '<br>';
}
But I still have these rows remaining, I need to try and do a str_replace between a line break and the end .mp3
D:\Music - Sorted\3 Doors Down\Away From The Sun\3 Doors Down - [Untitled Hidden Track].mp3
You can extract the relevant parts from source by use of preg_match_all with a regex like this.
$pattern = '/^#[^,\n]+,\K.*/m';
^ anchor matches start of line in multiline mode which is set with m flag.
#[^,\n]+, matches the part from # until , by use of a negated class.
\K is used to reset beginning of the reported match. We don't want the previous part.
.* the part to be extracted: Any amount of any character until end of the line.
if(preg_match_all($pattern, $finaloutput, $out) > 0);
print_r($out[0]);
PHP demo at eval.in
I'm using str_getcsv to parse tab separated values being returned from a nosql query however I'm running into a problem and the only solution I've found is illogical.
Here's some sample code to demonstrate (FYI, it seems the tabs aren't being preserved when showing here)...
$data = '0 16 Gruesome Public Executions In North Korea - 80 Killed http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata "North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou... 1384357511 http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw 0 The Young Turks 1 2013-11-13 12:53:31 9ab8f5607183ed258f4f98bb80f947b4 35afc4001e1a50fb463dac32de1d19e7';
$data = str_getcsv($data,"\t",NULL);
echo '<pre>'.print_r($data,TRUE).'</pre>';
Pay particular attention to the fact that one column (beginning with "North Korea...." actually starts with a double quote " but doesn't finish with one. This is why I supply NULL as the third parameter (enclosure) to override the defaut " enclosure value.
Here is the result:
Array
(
[0] => 0
[1] => 16
[2] => Gruesome Public Executions In North Korea - 80 Killed
[3] => http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata
[4] =>
[5] => North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou... 1384357511 http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw 0 The Young Turks 1 2013-11-13 12:53:31 9ab8f5607183ed258f4f98bb80f947b4 35afc4001e1a50fb463dac32de1d19e7
)
As you can see the quote is breaking the function. Logically I thought I would be able to use NULL or and empty string'' as the third parameter for str_getcsv (enclosure) but neither worked?!?!
The only thing I could use to get str_getcsv to work properly was a space char ' '. That doesn't make any sense to me becuase none of the columns have whitespace starting and/or ending them.
$data = '0 16 Gruesome Public Executions In North Korea - 80 Killed http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata "North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou... 1384357511 http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw 0 The Young Turks 1 2013-11-13 12:53:31 9ab8f5607183ed258f4f98bb80f947b4 35afc4001e1a50fb463dac32de1d19e7';
$data = str_getcsv($data,"\t",' ');
echo '<pre>'.print_r($data,TRUE).'</pre>';
Now the result is:
Array
(
[0] => 0
[1] => 16
[2] => Gruesome Public Executions In North Korea - 80 Killed
[3] => http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata
[4] =>
[5] => "North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou...
[6] => 1384357511
[7] => http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw
[8] => 0
[9] => The Young Turks
[10] =>
[11] =>
[12] =>
[13] =>
[14] => 1
[15] => 2013-11-13 12:53:31
[16] => 9ab8f5607183ed258f4f98bb80f947b4
[17] => 35afc4001e1a50fb463dac32de1d19e7
)
So my question is, why does it work with a space as the enclosure, but not NULL or and empty string? Also are there repercussions to this?
UPDATE 1: It seems this reduced the number of errors I was receiving in our logs but it didn't eliminate them, so I'm guessing that the I used as the enclosure has caused unintended side effects, albeit less troubling than the previous problem. But my question remains the same, why can't I use NULL, or an empty space as the enclosure, and secondly, is there a better way of dealing with / doing this?
Just to give a starting point ...
You might wanna consider working with the string itself, instead of using a function like str_getcsv in your case.
But be aware that there are at least some pitfalls, if you choose this route (might be your only option though):
Handling of escaped characters
Line breaks within the data (not meant as delimiters)
If you know that you don't have any other TABS in your string other than those ending the fields, and you don't have any linebreaks other than those delimiting a row, you might be fine with this:
$data = explode("\n", $the_whole_csv_string_block);
foreach ($data as $line)
{
$arr = explode("\t", $line);
// $arr[0] will have every first field of every row, $arr[1] the 2nd, ...
// Usually this is what I want when working with a csv file
// But if you rather want a multidimensional array, you can simply add
// $arr to a different array and after this loop you are good to go.
}
Otherwise this is just a starting point for you, to begin and tweak it to your individual situation, hope it helps.
Simply use chr(0) as enclosure and escape:
$data = str_getcsv($data, "\t", chr(0), chr(0));
I have a bizarre issue that I cannot for the life of me seem to resolve.
I am generating an array ($tags) from a mysql query, it looks something like this:
Array(
[1] => Safety Toe
[2] => Waterproof
)
Then I have another array ($link) I generate in a loop:
Array(
[1] => Array(
[0] => 1
[1] => 2
)
[2] => Array(
[0] => 1
[1] => 2
)
)
Also, I have 2 predefined variables that in this case are as follows:
$max == 2;
$title_count == 3;
Later on I have 2 for loops, 1 is nested:
for($y=0;$y<$max;$y++){
for($x=1;$x<=$title_count;$x++){
if($x==1){
echo "<tr><td>".$tags[$link[$x][$y]]."</td>";
}elseif($x<$title_count){
echo "<td>".$tags[$link[$x][$y]]."</td>";
}else{
echo "<td>".$tags[$link[$x][$y]]."</td></tr>";
}
}
}
This should produce something along the lines of:
Safety Toe Safety Toe Safety Toe
Waterproof Waterproof Waterproof
The problem is this is what I get:
Safety Toe Safety Toe Safety Toe
This made me curious, so I tried manually inputting $tags[2]. That worked and produced:
Waterproof Waterproof Waterproof
Waterproof Waterproof Waterproof
However, if I manually set them all to $tags[$link[1][1]] ($link[1][1] == 2) I get an empty result. If I set a variable, such as $test = $link[1][1]; (which echoes as 2), and then try $tags[$test], I get nothing. However if I set $test = 2; and do $tags[$test] I get Waterproof.
I am beyond bewildered here, if there is anything I'm missing, or any ideas as to why this would be the way it is, please let me know.
Thanks!
I figured out my problem, and it would not have been determinable from what I posted.
I tested
$tags[intval($links[1][1])]
and it worked.The $links array is being generated by exploding a string (1, 2). I was axploding on "," not ", " so the value of the second entry was " 2" instead of "2", hence the intval.
The string needs to be adjusted to "1,2" or the explode needs to be adjusted to ", ". Either way fixes the problem.
I have mysql search results from a keyword search being performed on my site. They're sorted by membership rank (0-3). However, I need to display the ranks differently than each other - like rank 3 gets more prominent formatting than the others.
I was thinking of splitting the rows up into individual arrays. So like array0 would contain all the rows that had the rank of 0, etc. Then loop through these arrays to display the results. I just have NO idea how to do this -- split the array up into smaller arrays.
(For reference, I found this question: splitting a large array into smaller arrays based on the key names but I wasn't really sure if that's what I needed... maybe some clarification on that q would help here?)
For example here is my array:
Array (
[rank] => 3
[organization] => Test Company
[imagecompany] => 1636.gif
[website] => http://www.google.com
[phone] => 344-433-3424
[fax] =>
[address_on_web] => physical
[address] => 2342 Test Ave
[city] => York
[stateprov] => WA
[postalcode] => 00000
[address_mailing] => 2342 Test Ave
[city_mailing] => Seattle
[state_mailing] => WA
[zip_mailing] => 00000
[description] => 'Test test Test test Test test Test test Test
test Test test Test test Test test Test test Test test Test test Test test Test test
Test test Test test'
[customerid] => 1636 )
You can use the rank as a key to create an multidimensional array like this:
$aRanks = array();
foreach($aArray as $aEntry) {
$aRanks[$aEntry['rank']][] = $aEntry;
}
echo '<pre>';
print_r($aRanks);
I have mysql search results from a keyword search
Then sort it using the database/SQL - not PHP. It's faster and uses less code.
$query = mysql_query(); // your query here
$result = mysql_fetch_array($query);
foreach($result as $row){
switch($row['rank']){
case 3:
// statement to apply formatting, add to each case
// example:
echo "<span style="color:red;">;
break;
case 2: break;
case 1: break;
}
}
Then output each row, echo closing </span> (or div or whatever) where you want the formatting to end