I've got a project that involves getting flight information from a database.
I want the results to look like:
01 Nov 2017 - Eastern Airways 7601
Departing from Southampton, Eastleigh (SOU) at 0840
However my code seems to bring up the below with a mysterious live of nonsense as per below
01 Nov 2017 - Eastern Airways 7601
Departing from , () at 084001 Nov 2017 - 7601 //this line I don't want
Departing from Southampton, Eastleigh (SOU) at 0840
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx' );
foreach ($flights as $b) {
$query = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30;";
$query .= "SELECT * FROM `airports` WHERE `Airport Code` = '$depdest' LIMIT 0 , 30;";
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print results */
{
$date=date_create($depdate);
echo "<b>" . date_format($date,"d M Y"). " - ". $row['airlinename']." ".$flightno. "</b><br/>";
echo "Departing from " .$row['City Name'].", ".$row['Airport Name']." (".$row['Airport Code'].") at " . $deptime;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
Can anyone see what I'm doing wrong?
Data base tables are as below
table 1 - Name "airports"
Airport ID City name Airport Code Airport Name Country name Country Abbrev. World Area Code
1, 108 Mile Ranch, ZMH , 108 Mile Ranch , Canada, CA, 906,
2, Aachen, AAH Aachen/Merzbruck, Germany, DE, 429,
3, Aachen, ZIU, Railway, Germany, DE, 429,
4, Aalborg, AAL, Aalborg, Denmark, DK, 419,
etc
table 2 - Name "airlines"
airline id, Iata, Airline Name
1, 0A, Amber Air,
2, 0B, Blue Air,
3, 0C, IBL Aviation,
etc
Thanks!
If I was to guess, I would say that there is a problem with the $b variable.
It seems your output is being written twice: the value "084001" in the middle of the second line looks to be the 0840 flight time from one entry, and then immediately starting the next entry as the date.
I would guess that the foreach is looping twice, instead of once, causing two outputs.
Could you do an output of the $b variable?
echo "<pre>";
print_r($b);
echo "</pre>";
Related
I have files which have contents that contain only "win" or "loss" like so:
win
win
loss
loss
loss
loss
win
loss
win
win
win
win
win
loss
loss
win
win
I would like to find the largest winning streak, which is the largest number of times that the word "win" has appeared on consecutive lines.
In the above example, "win" appears consecutively 2 , 1, 5 and 2 times.
so the largest win streak would be "5".
How can i use the Linux terminal or PHP to calculate this?
The only way i can think to do it is to look for "win" then use a large number of nested if statements to check the next line, but if the win streak was over 100+ then this would result in large amounts of code.
Is their examples of how this can be done more efficiently?
As there's still no PHP solution given to this question, and admittedly slightly more verbose than the solutions given in the comments... This might help:
<?php
$content = file_get_contents('winloss.txt');
$arr = explode("\r\n", $content);
$rep = repetition($arr);
echo $rep['response'];
function repetition(array $arr, $str1 = 'win', $str2 = 'loss')
{
$prevVal = null;
$count = 1;
foreach($arr as $key => $value) {
if($prevVal == $value) {
$count++;
$storeRep[$value][] = $count;
} else {
$count = 1;
}
$prevVal = $value;
}
$maxConsec[$str1] = max($storeRep[$str1]);
$maxConsec[$str2] = max($storeRep[$str2]);
$maxConsec['response'] = "largest winning streak : " . $maxConsec[$str1];
return $maxConsec;
}
output:
largest winning streak : 5
var_dump($rep):
array(3) {
["win"]=>
int(5)
["loss"]=>
int(4)
["response"]=>
string(26) "largest winning streak : 5"
}
$ uniq -c file | sort -rn | awk '$2=="win"{print $1; exit}'
5
You could do it all in awk of course:
awk '
$0!=prev { if (cnt > max[prev]) max[prev]=cnt; prev=$0; cnt=0 }
{ cnt++ }
END { if (cnt > max[prev]) max[prev]=cnt; print max["win"] }
' file
5
What surpises me, is that there also still is no pandas version. How is that possible?
import pandas
df= pd.read_csv('file.txt', names=['win_loss'], index_col=False)
df['group']=(df['win_loss'] != df['win_loss'].shift()).cumsum()
group_counts= df.groupby(df['group']).agg({'win_loss': 'first', 'group': 'count'}).groupby('win_loss').max()
print(group_counts.loc['win'])
As there still is not python version (which is a shame), I wanted to provide one:
fp= open('file.txt', 'rt')
oldline= None
line= fp.readline()
counts= dict()
currcount= 1
while line:
if line != oldline:
if oldline is not None and counts.get(oldline, 0) <= currcount:
counts[oldline]= currcount
currcount= 1
oldline= line
else:
currcount+= 1
line= fp.readline().strip()
print(counts['win'])
if counts.get(line, 0) <= currcount:
counts[line]= currcount
Btw, I would really love to know, how a python version performs in comparison to an awk version.
So now finally I can start with the COBOL version :-)
Here a version in COBOL. Slightly more verbose, than the other versions ;-)
You can simpy run it from a JCL in z/OS (loosely speaking: the bash version of z/OS):
IDENTIFICATION DIVISION.
PROGRAM-ID. WINCOUNT.
AUTHOR. JOTTBE.
*
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
*
SPECIAL-NAMES.
DECIMAL-POINT IS COMMA.
*
INPUT-OUTPUT SECTION.
FILE-CONTROL.
* ---CONTROL CARD
SELECT VCNT ASSIGN TO VCNT
ORGANIZATION SEQUENTIAL
ACCESS SEQUENTIAL
FILE STATUS VCNT-STATUS.
* ---INPUT FILE
SELECT CNT ASSIGN TO CNT
ORGANIZATION SEQUENTIAL
ACCESS SEQUENTIAL
FILE STATUS CNT-STATUS.
DATA DIVISION.
FILE SECTION.
* ---CONTROL CARD
FD VCNT
BLOCK CONTAINS 0 RECORDS
LABEL RECORD IS STANDARD
RECORDING MODE IS F.
01 VC-RECORD PIC X(080).
*----INPUT FILE
FD CNT
BLOCK CONTAINS 0 RECORDS
LABEL RECORD IS STANDARD
RECORDING MODE IS F.
01 C-RECORD PIC X(004).
WORKING-STORAGE SECTION.
01 PARMCARD.
* ---TEXT "SEARCH FOR: "
05 FILLER PIC X(012).
05 SEARCH-STRING PIC X(004).
05 FILLER PIC X(064).
01 INP-LINE.
05 STRING PIC X(004).
01 WORK.
05 LAST-STRING PIC X(004) VALUE " ".
05 LAST-COUNT PIC X(010) VALUE 0.
05 MAX-COUNT PIC X(010) VALUE 0.
01 K-CONSTANTS.
05 K-STATUS-OK PIC X(02) VALUE "00".
05 K-EOF PIC X(02) VALUE "10".
05 K-ERROR PIC X VALUE "E".
05 K-OK PIC X VALUE " ".
05 K-YES PIC X VALUE "Y".
01 S-SWITCHES.
05 S-PGM-STATUS PIC X VALUE " ".
05 S-ERROR PIC X VALUE " ".
05 S-END PIC X VALUE " ".
88 END-OF-PROCESSING VALUE "Y".
*
******************************************************************
PROCEDURE DIVISION.
******************************************************************
S00 SECTION.
INITIALIZE PARMCARD
INITIALIZE WORK
*
* ---OPEN FILES
*
* 1. PARAMETER CARD
OPEN INPUT VCNT
IF VCNT-STATUS = K-STATUS-OK
READ VCNT INTO PARMCARD
IF VCNT-STATUS = K-EOF
DISPLAY "ERROR OPENING THE PARAMETER CARD"
EXIT
END-IF
END-IF
* 2. INPUT FILE
OPEN INPUT CNT
IF CNT-STATUS = K-STATUS-OK
CONTINUE
ELSE
DISPLAY "ERROR OPENING THE INPUT FILE"
EXIT
END-IF
PERFORM UNTIL CNT-STATUS = K-EOF OR END-OF-PROCESSING
READ CNT INTO INP-LINE
AT END MOVE "Y" TO S-END
END-READ
IF STRING NOT = LAST-STRING
IF SEARCH-STRING = LAST-STRING
AND LAST-COUNT > MAX-COUNT
MOVE LAST-COUNT TO MAX-COUNT
END-IF
MOVE STRING TO LAST-STRING
MOVE 1 TO LAST-COUNT
END-IF
END-PERFORM
IF SEARCH-STRING = STRING
AND LAST-COUNT > MAX-COUNT
MOVE LAST-COUNT TO MAX-COUNT
END-IF
DISPLAY SEARCH-STRING " OCCURED " MAX-COUNT " TIMES."
EXIT.
Run it with a control card with the following content:
SEARCH FOR: WIN
Have fun.
I'm working on INSERTing VALUES using MySQL queries that involve escaping values via a PHP script. I was able write code that works (see below), but the only ways I can figure out are so cumbersome that they remind me of plebs eating peas off a fork at West Point. I have to believe I'm missing something. MySQL and PHP are supposed to work together, right? Can anyone point me in a better direction? Thanks!
<?php
// CONNECTION = "$connection".
require("Connection.php");
// CREATE TABLE
$create_table_query="
CREATE TABLE IF NOT EXISTS `titles_table`
(lastpost_id INT(10) NULL,
title VARCHAR(200))
";
$create_query_results=mysqli_query($connection,$create_table_query);
// Set up CUMBERSOME query:
$title1="IL - Yingying Zhang, 26, Urbana, 9 June 2017";
Echo "\$title1 looks like: $title1 <br>"; // 'IL - Yingying Zhang, 26, Urbana, 9 June 2017'
$title2="NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015";
Echo "\$title2 looks like: $title2 <br>"; // 'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015'
$title1_escaped="'".mysqli_real_escape_string($connection,$title1)."'";
Echo "\$title1_escaped looks like: $title1_escaped <br>";
$title2_escaped="'".mysqli_real_escape_string($connection,$title2)."'";
Echo "\$title2_escaped looks like: $title2_escaped <br>";
$sql_query_CUMBERSOME="
INSERT INTO `titles_table`(
lastpost_id,
title
)
VALUES
(1013,
$title1_escaped),
(1014,
$title2_escaped);
";
echo "<br>";
echo "Here's what \$sql_query_CUMBERSOME looks like :<br>";
echo "$sql_query_CUMBERSOME </br>";
// INSERT INTO `titles_table`( lastpost_id, title ) VALUES (1013, 'IL - Yingying Zhang, 26, Urbana, 9 June 2017'), (1014, 'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015');
// RUN and TEST $sql_query_CUMBERSOME
$sql_query_CUMBERSOME_results=mysqli_query($connection,$sql_query_CUMBERSOME);
// TEST the results (the tests report success)
IF(!$sql_query_CUMBERSOME_results):
$results_error_message=mysqli_error($connection);
ECHO "ERROR: \$sql_query_CUMBERSOME_results doesn't exist. The mysqli error message is: $results_error_message </br>";
ELSE:
$affected_rows=mysqli_affected_rows($connection);
ECHO "SUCCESS: \$sql_query_CUMBERSOME_results exists. Here is the affected rows count: $affected_rows </br></br>";
ENDIF;
// -----------------------------------
// SET UP alternative UNWIELDLY query:
$sql_query_UNWIELDLY = "INSERT INTO `titles_table`(lastpost_id,title) ";
$sql_query_UNWIELDLY .= "VALUES (1015,'";
$sql_query_UNWIELDLY .= mysqli_real_escape_string($connection,'IL - Yingying Zhang, 26, Urbana, 9 June 2017');
$sql_query_UNWIELDLY .= "'),";
$sql_query_UNWIELDLY .= "(1016,'";
$sql_query_UNWIELDLY .= mysqli_real_escape_string($connection,'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015');
$sql_query_UNWIELDLY .= "');";
echo "Here's what \$sql_query_UNWIELDLY looks like:<br>";
echo "$sql_query_UNWIELDLY </br>";
// INSERT INTO `titles_table`(lastpost_id,title) VALUES (1015,'IL - Yingying Zhang, 26, Urbana, 9 June 2017'),(1016,'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015');
// RUN and TEST $sql_query_UNWIELDLY
$sql_query_UNWIELDLY_results=mysqli_query($connection,$sql_query_UNWIELDLY);
// TEST the results (the tests report success)
IF(!$sql_query_UNWIELDLY_results):
$results_error_message=mysqli_error($connection);
ECHO "3a) ERROR: \$sql_query_UNWIELDLY_results doesn't exist. The mysqli error message is: $results_error_message </br>";
ELSE:
$affected_rows=mysqli_affected_rows($connection);
echo "SUCCESS: \$sql_query_UNWIELDLY_results exists. Here is the affected rows count: $affected_rows </br>";
ENDIF;
?>
I think the line of code looks good but, Only things we can use to close the connection after use.
End of your code add
mysqli_close($connection);
hope it will work, if not let me know.
Firstly, i am a php newbie... so i still code and understand php procedurally. that said,
i have a collection of numbers (amount) stored in a database.
Question: Using PHP and mySQL,
Whats the best way to spool this info out of a database such that the amount will be associated with its transaction ID
Most importantly, i need to find a matching set of numbers in the db that equals a sum of 29.
Below is the Transaction Table , Transaction_tlb, for my Database mydb
Transaction_ID | Name | Date | Amount
---------------|------------------|-----------------|------------
11012 | Jonathan May | 6/12/2016 | 84
21012 | John Pedesta | 6/12/2016 | 38
31012 | Mary Johnson | 1/01/2017 | 12
41012 | John Johnson | 8/01/2017 | 13
51012 | Keith Jayron | 8/01/2017 | 17
61012 | Brenda Goldson | 8/01/2017 | 2
71012 | Joshua Traveen | 8/01/2017 | 78
81012 | Remy ma Goldstein| 8/01/2017 | 1
91012 | Barbie Traveen | 8/01/2017 | 1
Now, i have an idea..but its not efficient. I am going to try every possible case. meaning if i have n values to check, the time complexity is going to be about 2^n. this is highly inefficient (plus, i dont even know if my code makes any sense. (see below)
I saw a similar example in this YouTube video: https://www.youtube.com/watch?v=XKu_SEDAykw&t
but, Im not sure exactly how to write the code in php.
The code:
<?php
if (!mysql_connect("localhost", "mysql_user", "mysql_password") || !mysql_select_db("mydb")) {
die("Could not connect: " . mysql_error()); } //End DB Connect
$capacity = 29; //Knapsack Capacity or Sum
//Select Transact ID and Value from the Database where Amount is <= Capacity
$fetchQuery = "SELECT 'Transaction_ID', 'Amount' FROM 'Transaction_tlb' WHERE 'Amount' <= $capacity";
$components = array(); //new array to hold components
if ($queryResults = mysql_query($fetchQuery)) {
//check if data was pulled
if (mysql_num_row($queryResults) != NULL) {
while ($row = mysqli_fetch_assoc($queryResults) {
$components[$row['Transaction_ID']] = $row['Amount'];
}
}
}
/* Correct me if i am wrong, but, Components associative array Should be something like
$components = array('11012'=> 84, '21012'=> 38, '31012'=> 12, '41012'=> 13, '51012'=> 17,
'61012'=> 2, '71012'=> 78, '81012'=> 1, '91012'=> 1);
*/
$components = asort($components) // sort array in ascending order
$componentCount = count($component)
function match ($componentCount, $capacity) {
$temp = match (($componentCount - 1), $capacity);
$temp1 = $component[$componentCount] + match (($componentCount - 1), ($capacity - $component[$componentCount]));
$result = max($temp, $temp1);
return $result;
}
}?>
can anyone please point me in the right direction? this code doesn work... and even if it works... the method is not efficient at all. what happens when Ive got 3 million records to work with? i need help please.
You can formulate your problem in terms of the 0/1 Knapsack problem. Ready-to-use implementation in PHP is available.
Using the function knapSolveFast2 defined in the linked page, one could proceed as in the example below. The idea here is that you set the "weights" entering the Knapsack algorithm equal to the values themselves.
$components = array(84, 38, 12, 13, 17, 2, 78, 1, 1);
$m = array();
list($m4, $pickedItems) = knapSolveFast2($components, $components, sizeof($components)-1, 29, $m);
echo "sum: $m4\n";
echo "selected components:\n";
foreach($pickedItems as $idx){
echo "\t$idx --> $components[$idx]\n";
}
which yields:
sum: 29
selected components:
2 --> 12
4 --> 17
Notes:
you could modify your SQL query in order to skip rows with amount larger than the required sum (29)
the function above will pick one solution (assuming that it exists), it won't provide all of them
one should check whether the return value $m4 is indeed equal to the specified sum (29) - as the algorithm works, the specified amount is only the upper limit which is not guaranteed to be attained (for example for 37 instead of 29, the return value is only 34 since there is no combination of the input numbers the sum of which would yield 37)
This is really a knapsack problem, but I will try to give a full solution which isn't optimal, but illustrates a full strategy for solving your problem.
First of all, you can do this with just one iteration over the array of numbers with no recursion and no pre-sorting needed. Dynamic programming is all you need, keeping track of all previously possible partial-sum 'paths'. The idea is somewhat similar to your described recursive method, but we can do it iteratively and without presorting.
Assuming an input array of [84, 38, 12, 13, 17, 2, 78, 1, 1] and a target of 29, we loop over the numbers like so:
* 84 - too big, move on
* 38 - too big, move on
* 12 - gives us a subtarget of 29-12 = 17
subtargets:
17 (paths: 12)
* 13 - gives us a subtarget of 29-13=16
subtargets:
16 (paths: 13)
17 (paths: 12)
* 17 - is a subtarget, fulfilling the '12' path;
and gives us a subtarget of 29-17=12
subtargets:
12 (paths: 17)
16 (paths: 13)
17 (paths: 12)
solutions:
12+17
etc.
The trick here is that while looping over the numbers, we keep a lookup table of subTargets, which are the numbers which would give us a solution using one or more combinations ('paths') of previously seen numbers. If a new number is a subTarget, we add to our list of solutions; if not then we append to existing paths where num<subTarget and move on.
A quick and dirty PHP function to do this:
// Note: only positive non-zero integer values are supported
// Also, we may return duplicate addend sets where the only difference is the order
function findAddends($components, $target)
{
// A structure to hold our partial result paths
// The integer key is the sub-target and the value is an array of string representations
// of the 'paths' to get to that sub-target. E.g. for target=29
// subTargets = {
// 26: { '=3':true },
// 15: { '=12+2':true, '=13+1':true }
// }
// We are (mis)using associative arrays as HashSets
$subTargets = array();
// And our found solutions, stored as string keys to avoid duplicates (again using associative array as a HashSet)
$solutions = array();
// One loop to Rule Them All
echo 'Looping over the array of values...' . PHP_EOL;
foreach ($components as $num) {
echo 'Processing number ' . $num . '...' . PHP_EOL;
if ($num > $target) {
echo $num . ' is too large, so we skip it' . PHP_EOL;
continue;
}
if ($num == $target) {
echo $num . ' is an exact match. Adding to solutions..' . PHP_EOL;
$solutions['='.$num] = true;
continue;
}
// For every subtarget that is larger than $num we get a new 'sub-subtarget' as well
foreach ($subTargets as $subTarget => $paths) {
if ($num > $subTarget) { continue; }
if ($num == $subTarget) {
echo 'Solution(s) found for ' . $num . ' with previous sub-target. Adding to solutions..' . PHP_EOL;
foreach ($paths as $path => $bool) {
$solutions[$path . '+' . $num] = true;
}
continue;
}
// Our new 'sub-sub-target' is:
$subRemainder = $subTarget-$num;
// Add the new sub-sub-target including the 'path' of addends to get there
if ( ! isset($subTargets[$subRemainder])) { $subTargets[$subRemainder] = array(); }
// For each path to the original sub-target, we add the $num which creates a new path to the subRemainder
foreach ($paths as $path => $bool) {
$subTargets[$subRemainder][$path.'+'.$num] = true;
}
}
// Subtracting the number from our original target gives us a new sub-target
$remainder = $target - $num;
// Add the new sub-target including the 'path' of addends to get there
if ( ! isset($subTargets[$remainder])) { $subTargets[$remainder] = array(); }
$subTargets[$remainder]['='.$num] = true;
}
return $solutions;
}
Run the code like so:
$componentArr = array(84, 38, 12, 13, 17, 2, 78, 1, 1);
$addends = findAddends($componentArr, 29);
echo 'Result:'.PHP_EOL;
foreach ($addends as $addendSet => $bool) {
echo $addendSet . PHP_EOL;
}
which outputs:
Looping over the array of values...
Processing number 84...
84 is too large, so we skip it
Processing number 38...
38 is too large, so we skip it
Processing number 12...
Processing number 13...
Processing number 17...
Solution(s) found for 17 with previous sub-target. Adding to solutions..
Processing number 2...
Processing number 78...
78 is too large, so we skip it
Processing number 1...
Processing number 1...
Solution(s) found for 1 with previous sub-target. Adding to solutions..
Result:
=12+17
=12+13+2+1+1
how to convert HTML data to json, example as below, description content how to convert as json, it is from mysql, php., how to send json responce as plain text, but description comes from the mysql db as it is, but how to send the json responce api to androind.
public function actionTestanalysis()
{
//echo $keyword=$_POST['keyword'];
$query= Yii::app()->db->createCommand("select * from test ORDER BY id DESC")->queryAll();
$arr = array();
if(count($query) > 0) {
foreach($query as $query){
$arr[] = $query;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
//exit;
}
json responce
[
{
"id": "99",
"name": "Max-Gain on or before 25th January 2016 in Max India Limited.",
"description": "
\r\n\tMax India Limited has announced the Record date for Three way De-Merger as 28th January 2016 (Thursday). <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tAnyone want to Gain from the three way De-Merger of Max India Group one should buy the shares of Max India Limited on or before – 25th January 2016 (Cum-Date – Monday Tentavily) otherwise to be on safer side you can buy on or before 22nd January 2016(Friday) and get invested in it.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tIf any investor invests for a period Of 12 – 18 Months , this scrip will be a Multifold - Multi Bagger.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tTo View the full report on Max India Limited authored . <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tPlease Click The Below Link<\/div>\r\n
\r\n\t
\r\n\t\thttp:\/\/www.test.com\/index.php\/newsOpportunities\/list\/scroll\/no-pain-all-gain-maximum-benefit-in-max-india-ltd<\/a><\/p>\r\n<\/div>\r\n",
"image": "",
"status": "unlock"
},
You have also one error in the cycle in your code.
Try this:
if (count($query) > 0) {
foreach ($query as $queryElement) {
$el = $queryElement;
$el['description'] = trim(preg_replace('/\s+/', ' ', strip_tags($el['description'])));
$arr[] = $el;
}
}
Try before: echo $json_response set header content type to application/json
<?PHP
header('Content-Type: application/json');
echo $json_response;
Use htmlentities() instead of strip_tags(), in order to retain actual content stored in db.
i am displaying the top 5 results from a sql query using the following code;
<?php
$query = "SELECT location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<span class='graphValue'>x".$row['qty']."</span> " . $row['location'] . "<br />";
} ?>
this is displaying my result strings as follows:
x46 Moon 20 - Sisters of EVE Academy
x34 Moon 7 - Ammatar Fleet Assembly Plant
x28 Jita x11 Jita IV - Moon 4 - Caldari Navy Assembly Plant
x11 Jita IV - Moon 4
x9 Lonetrek III - FUUUFAGOLAS
how can i trim down the $row['location'] to show the words before the first "-" for example;
x46 Moon 20
x34 Moon 7
x28 Jita x11 Jita IV
x11 Jita IV
x9 Lonetrek III
Just use strstr() and print before needle, e.g.
strstr($row['location'], "-", TRUE);
while you could do it with php as every on else suggest, i think its better to do it with mysql:
$query = "SELECT SUBSTRING_INDEX(location,'-',1) as location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5";
echo explode('-', $row['location'])[0];
OR
echo preg_replace('/\-\s.+/i', '', $row['location']);
$str='x46 Moon 20 - Sisters of EVE Academy';
$str2=substr($str,0,strpos($str,' -'));
echo $str2;
There's a couple different ways you could do this, one using explode()
$location = explode("-", $row['location']);
Then call everything before the "-" with echo $location[0]; See PHP Explode
Or you can use strstr()
$location = strstr($row['location'], '-', true);
and call it with just $location as setting the 3rd parameter to true returns everything before the first occurrence of the 2nd parameter. See PHP strstr
Or you can use split()
$location = split("-", $row['location']);
and call it using $location[0]