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
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'm using the the League CSV library, but the same exact thing happens when I use built in PHP functions. Here is my spreadsheet:
ID column A column B column C
123 apple orange pear
And here is my code:
$stmt = (new Statement())
->offset(0)
->limit(2)
;
$records = $stmt->process($csv);
foreach ($records as $record) {
print_r($record);
}
Finally, here is the output. Notice, the ID value (123) is hanging off to the left. I'm not even sure what that is supposed to mean.
Array
(
[0] => ID
[1] => column A
[2] => column B
123 [3] => column C
[4] => apple
[5] => orange
[6] => pear
)
Edit: Here is the raw CSV file. Newline character is possibly a carriage return?
ID,column A,column B,column C
123,apple,orange,pear
This was really lame. Since I'm on a Mac, I needed to add this line to the top of the script:
ini_set('auto_detect_line_endings',TRUE);
I'm working in PHP and need to parse strings looking like this:
Rake (100) Pot (1000) Players (andy: 10, bob: 20, cindy: 70)
I need to get the rake, pot, and rake contribution per player with names. The number of players is variable. Order is irrelevant so long as I can match player name to rake contribution in a consistent way.
For example I'm looking to get something like this:
Array
(
[0] => Rake (100) Pot (1000) Players (andy: 10, bob: 20, cindy: 70)
[1] => 100
[2] => 1000
[3] => andy
[4] => 10
[5] => bob
[6] => 20
[7] => cindy
[8] => 70
)
I was able to come up with a regex which matches the string but it only returns the last player-rake contribution pair
^Rake \(([0-9]+)\) Pot \(([0-9]+)\) Players \((?:([a-z]*): ([0-9]*)(?:, )?)*\)$
Outputs:
Array
(
[0] => Rake (100) Pot (1000) Players (andy: 10, bob: 20, cindy: 70)
[1] => 100
[2] => 1000
[3] => cindy
[4] => 70
)
I've tried using preg_match_all and g modifiers but to no success. I know preg_match_all would be able to get me what I wanted if I ONLY wanted the player-rake contribution pairs but there is data before that I also require.
Obviously I can use explode and parse the data myself but before going down that route I need to know if/how this can be done with pure regex.
You could use the below regex,
(?:^Rake \(([0-9]+)\) Pot \(([0-9]+)\) Players \(|)(\w+):?\s*(\d+)(?=[^()]*\))
DEMO
| at the last of the first non-capturing group helps the regex engine to match the characters from the remaining string using the pattern which follows the non-capturing group.
I would use the following Regex to validate the input string:
^Rake \((?<Rake>\d+)\) Pot \((?<Pot>\d+)\) Players \(((?:\w*: \d*(?:, )?)+)\)$
And then just use the explode() function on the last capture group to split the players out:
preg_match($regex, $string, $matches);
$players = explode(', ', $matches[2]);
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>
I have a list of courses and the hours they require for students to take them. The courses are as follows:
CON8101 Residential Building/Estimating 16 hrs/w
CON8411 Construction Materials I 4 hrs/w
CON8430 Computers and You 4 hrs/w
MAT8050 Geometry and Trigonometry 4 hrs/w
I have used this RegEx to extract the name of course and the hours each course takes each week. There are more than 4 courses, the 4 are examples above. There can be as many as 50 courses.
$courseHoursRegEx = "/\s[0-9]{1,2}\shrs/w/";
$courseNameRegEx = "/[a-zA-Z]{3}[0-9]{4}[A-Z]{0,1}\s?/[a-zA-Z]{3,40}/";
And applied the following function (not sure if 100% right) to extract the RegEx'd strings. Using $courseLine is the variable I saved the string of each line from a text document that early I have fopened. It keeps track of the total hours that has been extracted from the string.
$courses is an array of check boxes that the user enters in the html section
$totalHours += GetCourseHours($courseLine);
function GetCourseHours($couseLine)
{
if(!preg_match($courseHoursRegEx, $courseLine))
{
return $courseLine;
}
}
function GetCourseName($courseLine)
{
if(!preg_match($courseNameRegEx, $courseLine))
{
return $courseLine;
}
}
I used a foreach loop to output all the selected courses to be sorted out in a table.
foreach($courses as $course)
{
$theCourse = GetCourseName($course);
$theHours = GetCourseHours($course)
}
Edit: output code
for($i = 1; $i <= $courses; ++$i)
{
printf("<tr><td>\$%.2f</td><td>\$%.2f</td></tr>", $theCourse, $theHours);
}
I am not sure how to output what I have into a dynamic table organized by the course name, and hours for each course. I cannot get my page to run, I cannot find any syntax errors, I was afraid it was my logic.
First of all, (after fixing a few minor things within the regexes) you can do all of that in one preg_ call. Here is how:
preg_match_all("~([a-zA-Z]{3}\d{4}[A-Z]{0,1}\s.+)\s(\d{1,2})\shrs/w~", $str, $matches);
$str can either be a multiline string with all rows at once. Or you can pass in a single line at a time. If you pass in all lines at once, $matches will afterward look like this:
Array
(
[0] => Array
(
[0] => CON8101 Residential Building/Estimating 16 hrs/w
[1] => CON8411 Construction Materials I 4 hrs/w
[2] => CON8430 Computers and You 4 hrs/w
[3] => MAT8050 Geometry and Trigonometry 4 hrs/w
)
[1] => Array
(
[0] => CON8101 Residential Building/Estimating
[1] => CON8411 Construction Materials I
[2] => CON8430 Computers and You
[3] => MAT8050 Geometry and Trigonometry
)
[2] => Array
(
[0] => 16
[1] => 4
[2] => 4
[3] => 4
)
)
Now you can simply iterate over all names in $matches[1] and sum up the hours in $matches[2]. Notice that those two inner arrays correspond to what's inside of the round brackets I used in the regex. These are so called subpatterns, and they capture additional (sub-)matches. Also $matches[0] will always contain the full match of the whole pattern, but you don't need that in this case.