I have the following text file:
::: Student Exam :::
Name: John Cage
Score: 5
Witness: Maria McCain
::: End Exam :::
::: Student Exam :::
Name: John Cage
Score: 5
Witness: Calvin Gilbert
::: End Exam :::
I'm parsing it using this code:
$db = file_get_contents(dirname(__FILE__) . '/exams.txt', TRUE);
$nl = "\r\n";
preg_match_all("|::: Student Exam :::(.*?)::: End Exam :::|s", $db, $exams);
foreach($exams[1] as $exam) {
preg_match("|Name: (.*?)$nl|s", $exam, $name);
preg_match("|Score: (.*?)$nl|s", $exam, $score);
preg_match("|Witness: (.*?)$nl|s", $exam, $witness);
if($score[1] < 4) {
// Something Here
}
}
I need, if the score is under 4, the exam must be removed from the file. How this can be done?
Create an empty array
$goodExams = array()
And push exams into it:
if($score[1] >= 4) {
$goodExams[] = $exam;
}
Or:
if($score[1] >= 4) {
$goodExams[] = array('name' => $name[1], 'score'=>$score[1], 'witness'=>$witness[1]);
}
$newTxt = "";
foreach($goodExams as $exam){
$newTxt.="::: Student Exam :::" . PHP_EOL;
// concatenae your data here
$newTxt.="::: End Exam :::" . PHP_EOL;
}
file_put_contents($filename, $newTxt)
After that you can process the goodExams array and dump your textfile.
Related
I have an script for getting a table from a DB which is written in PHP.
I am trying to add name for each column to be in the first row:
A part of the Code is:
$rows = [];
foreach (range(1, 4) as $row) {
$rows[$row] = "";
}
$rows["Name"] = $order->user->aFirstName;
$rows["Last Name"] = $alumn->aLastName;
$rows["Age"] = $alumn->aAge;
$rows["Gender"] = $alumn->aGender;
$string = "";
foreach ($rows as $r) {
$string .= $r . "\t";
}
what I want to get is
1 | Name | Last Name | Age | Gender
2 | John | Des | 45 | Male.
What I get now is the data in 1st row.
1 | John | Des | 45 | Male.
Any suggestion? Thanks
You can create a new first element in $rows using https://www.php.net/manual/de/function.array-unshift.php
$labels = ["Name" => "NameLabel", "Last Name" => "Last NameLabel" ...];
array_unshift($rows, $labels);
So the first element of the $rows array are the labels. Now when the table is generated is will display the labels at the top.
You are loading the arrays incorrectly.
I assume you dont want to get the column names from the meta data available to you, and are happy to add the column names manually, if not let me know
$rows = [];
// add labels
$rows[] = ["Name", "Last Name", "Age", "Gender"];
#$rows[] = [$order->user->aFirstName, $alumn->aLastName, $alumn->aAge, $alumn->aGender];
// I dont have your data, so this is to simulate the above line
$rows[] = ['John', 'Des', 45, 'Male'];
$string = '';
foreach ($rows as $i => $row) {
$n = $i+1;
$string .= "$n\t";
foreach ($row as $col){
$string .= $col . "\t";
}
$string .= '<br>'. PHP_EOL;
}
print_r($string);
RESULTS, as you can see a Tab is not really enough to correctly format the table
1 Name Last Name Age Gender <br>
2 John Des 45 Male <br>
I have a form on my site for the users to post a results report into,
the report looks like this:
Nojoks's Tourney Bracket Tool Version 1.2.1.84
Tournament: 3/5 Backgammon 1:00pm
Date: 01/22/2017
Day: Sunday
Scheduled Start: 1.00pm PST
Actual Start: 20:00:30
Closed: 20:11:00
Host: Waiter ()
Number of Players: 15
1st place: poppop
1st place email: bobmitch1170#gmail.com
2nd place: Sarge
2nd place email: rgarvey5#hotmail.com
3rd place: Litigolfer
3rd place email: dostrow2008#gmail.com
3rd place: PhantomMask
3rd place email:
START POINTS
burnieboy 5
EU_BNL_Chris1 5
EU_IT_VIANG 5
GennaLee 5
happybear 5
MC_Vicky 5
merceaviles 5
MRC_cadet 5
poeticfool 5
UBG_Angel_D_8 5
UBG_sara1smoon 5
Litigolfer 60
PhantomMask 60
Sarge 90
poppop 120
STOP POINTS
this report is going to be identical everytime with some minor changes
I have already split this into an array with explode
$records = explode( PHP_EOL, $_POST['points'] );
$records = array_map('htmlspecialchars', $records );
$records = array_map ('trim', $records);
Then i have work on collecting the information from the top of the report like so:
// Get Date
$date = substr($records[2], 7, 10);
echo "<b>Tournament Date: </b>" . $date . "<br />";
// Get star time
$start_time = substr($records[4], 18, 7);
echo "<b>Tournament Start Time: </b>" . $start_time . "<br />";
now i need to work on everything from $records[20] down
what i need to do is simple enough i just do not know how to get to the correct part of my array first
I used to ask my users to post only the information from the START POINTS line down to STOP POINTS so to get my information out and split was simple i used:
foreach( $records as $record ) {
$lastSpace = strrpos( $record, ' ' );
$player = trim( substr( $record, 0, $lastSpace ) );
$points = trim( substr( $record, $lastSpace+1 ) );
this code will still work in this case if i can drop the index's 0 - 19 or just split the array into a new array $records1
P.S its this section in the report that is ever changing so to speak this report is from a online tournament hosting tool and each tournament has no set amount of players it can range from 8 upwards
I'm not sure I understand what you need. Perhaps something like this?
The idea is that you search for the indexes in the array which contain the start and end of the points and do a for loop to iterate only over those points.
$start = array_search("START POINTS", $records);
$end = array_search("END POINTS", $records);
$playerArray = [];
for ($i = $start+1;$i < $end;$i++) {
$parts = explode(" ",$records[$i]);
$player = $parts[0];
$points = $parts[1];
$playerArray = [ "player" => $player, "points" => $points ];
}
I managed to work this problem out for myself with thanks to #apokryfos your code still did not do quiet what i wanted so i used your codes and added them into what i have now,
Here is what i came up with:
// New try to split a full report in one go.
$points = $date = $day = $start_time = $host = $number_of_players = $fp_name = $fp_email = $sp_name = $sp_email = "";
// Explode the string at the end of each line,
// array map and remove any special chars then trim white space.
$records = explode( PHP_EOL, $_POST['points'] );
$records = array_map('htmlspecialchars', $records );
$records = array_map ('trim', $records);
// now each line of the NJ's report is in an array, call the array $records[index number]
// use substr( , , ) to find the needed part of the array indexs,
// I.E in the array $records on line 2 is the Date the actual needed information is the date dd/mm/yyyy,
// so we use $date = substr($records[2], 7, 10);
// from this string : Date: 01/18/2017 which is line 2 in records we get the 01/18/2017
// Get Date
$date = substr($records[2], 7, 10);
echo "<b>Tournament Date: </b>" . $date . "<br />";
// Get star time
$start_time = substr($records[4], 18, 7);
echo "<b>Tournament Start Time: </b>" . $start_time . "<br />";
// get Host name
$host = substr($records[7], 7);
echo "<b>Tournament Host: </b>" . $host . "<br />";
// get number of players
$number_of_players = substr($records[8], 20);
echo "<b> Number Of Players: </b>" . $number_of_players . "<br />";
echo "<br />";
// get the first place name and email address
$fplaceName = substr($records[10], 12);
echo "<b>1ST place: </b>" . $fplaceName . "<br />";
$fplaceEmail = substr($records[11], 18);
echo "<b>1ST place Email: </b>" . $fplaceEmail . "<br />";
// Get second place name and email
$splaceName = substr($records[12], 12);
echo "<b>2ND place Email: </b>" . $splaceName . "<br />";
$splaceEmail = substr($records[13], 18);
echo "<b>2ND place Email: </b>" . $splaceEmail . "<br />";
// get third place name and email
$tplaceName = substr($records[14], 12);
echo "<b>3RD place Email: </b>" . $tplaceName . "<br />";
$tplaceEmail = substr($records[15], 18);
$t1placeEmail = "fake#fake.com";
if($tplaceEmail == "") { // if third place email is empty add a generic fake email else continue as normal
$tplaceEmail = $t1placeEmail;
} ;
echo "<b>3RD place Email: </b>" . $tplaceEmail . "<br />";
echo "<hr /><br /><br />";
// Getting the players and points.
$parts1 = array_slice($records, 20, -1);
$end = array_pop($parts1);
$records = array_map('htmlspecialchars', $records );
$records = array_map ('trim', $records);
foreach( $parts1 as $record ) {
$lastSpace = strrpos( $record, ' ' );
$player = trim( substr( $record, 0, $lastSpace ) );
$points = trim( substr( $record, $lastSpace+1 ) );
echo $player . " " . " " . " " . $points . "<hr /><br />";
}
so what happens is, some user pastes the report as above in my original post,
and hits submit,
the form posts to my processing.php page,
I explode the whole post "string" into an array $records,
array_map the htmlspecialchars and trim the records,
then there is all the codes to extract the Date, time, host, number of players,
Then we get the 1st, 2nd, 3rd names and email address's,
then we get to sorting the playernames and points,
array_slice from the line after STOP POINTS index[20] also -1 for the STOP POINTS index,
pop the last line from the array "STOP POINTS" gone,
re do the array_map's on the new array,
run a foreach loop on the new array using a lastSpace strpos " " and the new array
then split player name from points....
if i run the finished code on the report given in my original post you get the following output:
Music Cafe Tournament Date: 01/22/2017 Tournament Start Time: 1.00pm
Tournament Host: Waiter () Number Of Players: 15
1ST place: poppop 1ST place Email: bobmitch1170#gmail.com 2ND place
Email: Sarge 2ND place Email: rgarvey5#hotmail.com 3RD place Email:
Litigolfer 3RD place Email: dostrow2008#gmail.com
burnieboy 5
EU_BNL_Chris1 5
EU_IT_VIANG 5
GennaLee 5
happybear 5
MC_Vicky 5
merceaviles 5
MRC_cadet 5
poeticfool 5
UBG_Angel_D_8 5
UBG_sara1smoon 5
Litigolfer 60
PhantomMask 60
Sarge 90
poppop 120
of course with the rule separating each name and points,
which is what i needed and now i can add all my sql statements and bingo.
please if anyone can see an easier or better way to achieve this goal i would love to see your edits and test them out
I have view cart session like this
ID NAME DISC QTY
-- ---- ------ ------
1 AAAA D1 2
1 AAAA D5 1
2 BBBB D1 1
1 AAAA D1 1
What I want is, showing a query session with result like this
NAME TOTAL
---- ------
AAAA 4
BBBB 1
How can I do this?
I have a query like this for show cart:
<?php
if(count($_SESSION[data1][ID])>0)
for($i=0;$i<count($_SESSION[data1][ID]);$i++)
{
if($_SESSION[data1][ID][$i]!='')
{ ?>
<td ><?=$_SESSION[data1][ID][$i]?></td>
<td ><?=$_SESSION[data1][NAME][$i]?></td>
<td ><?=$_SESSION[data1][DISC][$i]?></td>
<td ><?=$_SESSION[data1][QTY][$i]?></td>
<?php } } ?>
You can simply loop through the data adding the quantities to an array indexed by the name.
Quick'n'dirty example
<?php
$names = array("AAA", "BBB", "AAA", "BBB");
$qts = array(1, 2, 3, 4);
for ($i=0; $i<count($names); $i++)
{
$res[$names[$i]] += $qts[$i];
}
$k = array_keys($res);
for ($i=0; $i<count($k); $i++)
{
echo $k[$i] . ":" . $res[$k[$i]] . "<br/>";
}
?>
AAA:4
BBB:6
You can create a new array $resultArray and take $_SESSION['data1'] in foreach loop, and check if ID does exists in $resultArray, if yes, append it, other wise create it.
<?php
$resultArray = array();
if(count($_SESSION['data1'])>0){
foreach($_SESSION['data1'] as $data){
if(isset($resultArray[$data['ID']])){
$resultArray[$data['ID']] += $data['QTY'];
} else {
$resultArray[$data['ID']] = $data['QTY'];
}
}
}
print_r($resultArray); //check out result
?>
When I just had single variables I used the compact array function to create an array containing variables and their values and looped through them, but now I have multiple variables in a 'group' to loop through:
$details_room_name_1
$details_room_photo_1
$details_room_capacity_seated_1
$details_room_name_2
$details_room_photo_2
$details_room_capacity_seated_2
$details_room_name_2
$details_room_photo_2
$details_room_capacity_seated_2
I want to loop through each 'GROUP' (room) of variables at a time
loop
echo room name
print_r room photo array
echo capacity
Using array is better (the best) solution for this task, but if the data structure has to be as you wrote (I donĀ“t know Wordpress), you can use st. like this ugly code.
<?php
$details_room_name_1 = 'room 1';
$details_room_photo_1 = 'photo 1';
$details_room_capacity_seated_1 = 1;
$details_room_name_2 = 'room 2';
$details_room_photo_2 = 'photo 2';
$details_room_capacity_seated_2 = 5;
$details_room_name_3 = 'room 3';
$details_room_photo_3 = 'photo 3';
$details_room_capacity_seated_3 = 8;
for ($i = 1; $i <= 10; $i++) {
if (!isset(${'details_room_name_' . $i})) continue;
echo 'room name: ' . ${'details_room_name_' . $i} . '<br>';
echo 'room photo: ' . ${'details_room_photo_' . $i} . '<br>';
echo 'room capacity: ' . ${'details_room_capacity_seated_' . $i} . '<br><br>';
}
/*
returns
room name: room 1
room photo: photo 1
room capacity: 1
room name: room 2
room photo: photo 2
room capacity: 5
room name: room 3
room photo: photo 3
room capacity: 8
*/
I am pulling college classes and details out of a MySQL database and sorting them onto a webpage with PHP.
Currently my script is simple. It pulls several fields and organizes them by class title:
Class name: Programming 101
Credit hours: 4
Time: 11:00am - 12:50pm
Days: M T W
Room #: 361
Sometimes we have 3 or 4 of the same class going on, so this can create a rather long page.
I'm trying to simplify the way the page looks.
So instead of having repeated class names:
Class name: Programming 101
Credit hours: 4
Time: 11:00am - 12:50pm
Days: M T W
Room #: 361
Class name: Programming 101
Credit hours: 4
Time: 11:30am - 2:50pm
Days: Th F
Room #: 123
You could see this:
Class name: Programming 101
Credit hours: 4
Time: 11:00am - 12:50pm
Days: M T W
Room #: 361
Time: 11:30am - 2:30pm
Days: Th F
Room #: 123
Class name: Programming 102
Credit hours: 4
Time: 1:00am - 2:30pm
Days: M W
Room #: 231
Time: 2:30am - 4:30pm
Days: T F
Room #: 222
Here is my current script:
$sql = "SELECT crs_title, trm_cde, last_name, first_name, begin_dte, end_dte, crs_cde, begin_tim, end_tim, monday_cde, tuesday_cde, wednesday_cde, thursday_cde, friday_cde, saturday_cde, sunday_cde, bldg_cde, room_cde, udef_5_2_1, crs_capacity, crs_enrollment, section_sts FROM BTC_Web_Schedule_view WHERE yr_cde = 2014 AND trm_cde = 'fa' ORDER BY crs_title, trm_cde";
$rs = odbc_exec($conn,$sql);
while (odbc_fetch_row($rs))
{
$crs_title = odbc_result($rs,"crs_title");
$trm_cde = odbc_result($rs,"trm_cde");
$crs_cde = odbc_result($rs,"crs_cde");
$begin_tim = odbc_result($rs,"begin_tim");
$end_tim = odbc_result($rs,"end_tim");
$begin_time = substr($begin_tim, 11, -7);
$end_time = substr($end_tim, 11, -7);
$begin_dte = odbc_result($rs,"begin_dte");
$end_dte = odbc_result($rs,"end_dte");
$monday_cde = odbc_result($rs,"monday_cde");
$tuesday_cde = odbc_result($rs,"tuesday_cde");
$wednesday_cde = odbc_result($rs,"wednesday_cde");
$thursday_cde = odbc_result($rs,"thursday_cde");
$friday_cde = odbc_result($rs,"friday_cde");
$saturday_cde = odbc_result($rs,"saturday_cde");
$sunday_cde = odbc_result($rs,"sunday_cde");
$first_name = odbc_result($rs,"first_name");
$last_name = odbc_result($rs,"last_name");
$fullname = $first_name.$last_name;
$bldg_cde = odbc_result($rs,"bldg_cde");
$room_cde = odbc_result($rs,"room_cde");
$udef_5_2_1 = odbc_result($rs,"udef_5_2_1");
$crs_capacity = odbc_result($rs,"crs_capacity");
$crs_enrollment = odbc_result($rs,"crs_enrollment");
$seats_left = $crs_capacity - $crs_enrollment;
$section_sts = odbc_result($rs,"section_sts");
echo "<div class='container'><p><h2>$crs_title</h2> | $crs_cde</p></div>";
echo "<div class='panel'><p><strong>Time</strong>: ".date('g:ia', strtotime($begin_time))." - ".date('g:ia', strtotime($end_time))."<br>";
echo "<strong>Start date</strong>: ".date("F jS, Y",strtotime($begin_dte))."<br>";
echo "<strong>End date</strong>: ".date("F jS, Y",strtotime($end_dte))."<br>";
echo "<strong>Days</strong>: $monday_cde $tuesday_cde $wednesday_cde $thursday_cde $friday_cde $saturday_cde $sunday_cde <br>";
echo "<strong>Instructor</strong>: $fullname <br>";
echo "<strong>Building</strong>: $bldg_cde <br>";
echo "<strong>Room</strong>: $room_cde <br>";
echo "<strong>Fee</strong>: $$udef_5_2_1 <br>";
echo "<strong>Seats remaining</strong>: $seats_left <br>";
echo "<strong>Enrollment status</strong>: $section_sts</p></div>";
}
odbc_close($conn);
I appreciate any advice. Thank you.
Normalize your database?
Other then that:
while (odbc_fetch_row($rs))
{
$crs_title = odbc_result($rs,"crs_title");
$first_name => odbc_result($rs,"first_name");
$last_name => odbc_result($rs,"last_name");
$fullname = $first_name.$last_name;
$begin_tim = odbc_result($rs,"begin_tim");
$end_tim = odbc_result($rs,"end_tim");
$crs_capacity = odbc_result($rs,"crs_capacity");
$crs_enrollment = odbc_result($rs,"crs_enrollment");
$courses[$crs_title][] = array(
$trm_cde = odbc_result($rs,"trm_cde")
'crs_cde' => odbc_result($rs,"crs_cde"),
'begin_tim' => $begin_tim,
'begin_time' => substr($begin_tim, 11, -7),
'end_tim' => $end_tim,
'end_time' = substr($end_tim, 11, -7),
'begin_dte' => odbc_result($rs,"begin_dte"),
'end_dte' => odbc_result($rs,"end_dte"),
'monday_cde' => odbc_result($rs,"monday_cde"),
'tuesday_cde' => odbc_result($rs,"tuesday_cde"),
'wednesday_cde' => odbc_result($rs,"wednesday_cde"),
'thursday_cde' => odbc_result($rs,"thursday_cde"),
'friday_cde' => odbc_result($rs,"friday_cde"),
'saturday_cde' => odbc_result($rs,"saturday_cde"),
'sunday_cde' => odbc_result($rs,"sunday_cde"),
'first_name' => $first_name,
'last_name' => $last_name,
'fullname' => $first_name.$last_name,
'bldg_cde' => odbc_result($rs,"bldg_cde"),
'room_cde' => odbc_result($rs,"room_cde"),
'udef_5_2_1' => odbc_result($rs,"udef_5_2_1"),
'crs_capacity' => $crs_capacity,
'crs_enrollment' => $crs_enrollment,
'seats_left' = $crs_capacity - $crs_enrollment,
'section_sts' => odbc_result($rs,"section_sts"),
);
foreach ($courses as $crs_title => $data) {
/* html output */
$count = count($data);
foreach ($data as $subdata) {
//multiple times
}
}
}
A few things to consider:
Change your query to do as much of the sorting as possible before even retrieving the data. For example, you could ORDER BY course title first (then secondarily by other fields like start date).
Build an array from the data such that you can easily output in teh way you want: For example:
$array = array();
while (odbc_fetch_row($rs)) {
// ... get your data (probably use something besides odbc_result so you can get ther whole array at once .. but for this example just assume I am using your same variables.
$array[$crs_title] = array(
// place your other course data here in array
);
}
foreach($array as $course_title => $course_data) {
// present your data
}