PHP String Comparision - php

I am using below PHP function in Behat Mink to check the Email column values are in ascending or descending order.But the problem is its always fails.I just want to check if the subject or From of Email column in all rows are in ascending and descending order.Is there are any other way to do this?
public function ValidateColumnSorting($Column, $order) {
$nodes = // Logic goes to retrieve all rows subject or from column value
if (strcasecmp($order, "asc") == 0)
{
for ($i = 1; $i < $sizeof($nodes); $i++)
{
if (strcasecmp($nodes[$i], $nodes[$i - 1]) >= 0)
{
print_r("Row " . $i - 1 . " val is " . $nodes[$i - 1]);
}
else if (strcasecmp($nodes[$i], $nodes[$i - 1]) < 0)
{
throw new Exception($Column . " column ascending sort order failed.".$nodes[$i] . " is less than " . $nodes[$i - 1]);
}
}
}
else
{
for ($i = 1; $i < $sizeof($nodes); $i++)
{
print_r($Column . " column row " . $i . " value is " . $nodes[$i]);
if (strcasecmp($nodes[$i], (string) $nodes[$i - 1]) <= 0) {
print_r($Column . " of Email is same");
} else if (strcasecmp($nodes[$i], $nodes[$i - 1]) > 0) {
throw new Exception($Column . " column descending sort order failed." . $nodes[$i] . " is greater than " . $nodes[$i - 1]);
}
}
}
}

Instead of checking for its order, you can directly sort it in ascending or descending order.
Pass subject or email array to sort() function
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
It will return the sorted array
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
You don't need to do it manually.
Read more here http://in2.php.net/sort

Without thinking if there is a more Behat appropriate way of validating the order of elements, your code would probably fail due to $sizeof($nodes), try sizeof($nodes) instead.
In Behat, the approach I would take would be to create a generic step definition which could be re-used elsewhere...
Then I should see the "css_to_some_elements" ordered as:
| apple |
| banana |
| lemon |

Related

Win Rate calculation - Php and api from leaguepedia

i'm using the api from leaguepedia to receive the informations.
So I have this code to show how many times a champion was picked in a tournament, its working fine, but
right now im trying to show the winrate and i'm having problems,
for example :
Syndra picked 4 Times - Won 3 times - winrate = 75%, thats the result i expect;
Gragas picked 3 Times - Won 3 times - winrate = 100%, thats the result i expect;
what im recieving is :
Syndra picked 4 Times - Won 1 time - winrate = 25%
Gragas picked 3 Times - Won 1 time - winrate = 33,33% , victory is showing 1 for every champion (image)
i know that my problem might be on the "switch / case", but i don't know how to fix
so how can i fix my code to show the properly win rate.
thanks
thats my code
<?php
// $Result is a CURL coming from leaguepedia api
$result = json_decode($file_contents);
$heroPicks = [];
$heroVictory = [];
// Double foreach to access the values from leaguepedia api
foreach ($result as $d) {
foreach ($d as $data) {
//$data->title->Team1Picks and
// $data->title->Team2Picks is coming from leaguepedia api
//as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
// So i need to explode and merge to an array to count.
$picks1 = explode(",", $data->title->Team1Picks);
$picks2 = explode(",", $data->title->Team2Picks);
$picks = array_merge($picks1, $picks2);
// this switch is to check if
// $data->title->Winner == 1 , it means that
// $picks1 won the game else == 2 $picks2
// won the game ($data->title->Winner is coming from api aswell)
switch ($data->title->Winner) {
case 1:
$w = $picks1;
break;
case 2:
$w = $picks2;
break;
}
//foreach to count the times a champion was picked
foreach ($picks as $pick) {
$pick = trim($pick);
if (!array_key_exists($pick, $heroPicks)) {
$heroPicks[$pick] = 0;
}
$heroPicks[$pick] += 1;
}
//foreach to count how many times a champion won a game
foreach ($w as $victory) {
$victory = trim($victory);
if (!array_key_exists($victory, $heroVictory)) {
$heroVictory[$victory] = 0;
}
$heroVictory[$victory] += 1;
}
}
}
//sorting the arrays
uasort(
$heroPicks,
function ($a, $b) {
return $a - $b;
}
);
uasort(
$heroVictory,
function ($c, $d) {
return $c - $d;
}
);
$heroPicks = array_reverse($heroPicks);
$heroVictory = array_reverse($heroVictory);
//foreach to show the results
echo "Best picks:" . PHP_EOL . "<br />";
foreach ($heroPicks as $heroName => $pickCount) {
foreach ($heroVictory as $heroVictoryName => $totalVictory) {
$total = ($totalVictory * 100) / $pickCount;
}
echo $heroName . " - " . $pickCount . PHP_EOL . " - Victorys = " . $totalVictory . " -- winrate :" . $total . "%" . "<br />";
}
?>
the $result variable for #bassxzero
The outer foreach will loop through all of your heroes that were picked. This is what you want.
The inner foreach is looping through all of your heroes' victories, regardless of the hero the outer loop is currently processing. All the victories are set to 1 because that is how many victories the last hero in your victory array has. This is not what you want.
You don't want a second inner foreach. You just want to lookup the victory stats for the hero currently being processed by the outer foreach.
foreach ($heroPicks as $heroName => $pickCount) {
$totalVictory = $heroVictory[$heroName] ?? 0;
$total = ($totalVictory * 100) / $pickCount;
echo $heroName . " - " . $pickCount . PHP_EOL . " - Victorys = " . $totalVictory . " -- winrate :" . $total . "%" . "<br />";
}

How to unset xml elements in php?

I am working on a php code as shown below in which I to want unset xml elements in php.
I have applied the logic in the following way:
When $a is 4, then it should display 4th item from the top from xml.
When $a is 3, then it should display 3rd item from the top from xml.
When $a is 2, then it should display 2nd item from the top from xml.
When $a is 1. then it should display 1st item from the top from xml.
At this moment, I have set value of a to 4.
$a=4;
if ($a == 1) { // it would not unset item[0] and it should display item[0] (April 5)
for($i = count($xml->channel->item); $i >= 1; $i--){
unset($xml->channel->item[$i]);
}
} else if ($a == 2) { // it would not unset item[1] and it should display item[1] (April 4)
for($i = count($xml->channel->item); $i >= 2; $i--){
unset($xml->channel->item[$i]);
}
unset($xml->channel->item[0]);
} else if ($a == 3) { // it would not unset item[2] and it should display item[2] (April 3)
for($i = count($xml->channel->item); $i >= 3; $i--){
unset($xml->channel->item[$i]);
}
unset($xml->channel->item[0]);
unset($xml->channel->item[1]);
} else if ($a == 4) { // it would not unset item[3] and it should display item[3] (April 2)
for($i = count($xml->channel->item); $i >= 4; $i--){
unset($xml->channel->item[$i]);
}
unset($xml->channel->item[0]);
unset($xml->channel->item[1]);
unset($xml->channel->item[2]);
} else if ($a == 5) { // it would not unset item[4] and it should display item[4] (April 1)
unset($xml->channel->item[0]);
unset($xml->channel->item[1]);
unset($xml->channel->item[2]);
unset($xml->channel->item[3]);
}
The above code is not working properly. All the content is being pulled from this xml http://www.cpac.ca/tip-podcast/jwplayer.xml
I have attached the screenshot with the list of items.
If you want to display the information from a particular element, you can just access it directly by its index, without deleting the other entries. This code will work on the XML downloaded from the URL in your question. Note that xml element arrays are 0-indexed so a value of 2 will get the third entry in the array, so we use $a-1 so that a value of 3 corresponds to the third entry. Also note the slight complexity due to some of the children having a different namespace...
$xml = simplexml_load_string($xmlstr);
$a = 3;
$item = $xml->channel->item[$a-1];
echo "Title: " . $item->title . "\n";
echo "Description: " . $item->description . "\n";
$jw = $item->children('jwplayer', true);
echo "Image: " . $jw->image . "\n";
echo "Source: " . $jw->source->attributes()->file . "\n";
Output:
Title: April 3, 2019
Description: Jody Wilson-Raybould and Jane Philpott are removed from the Liberal Caucus. Gerald Butts submits text messages, and other evidence, to the justice committee. The Environment Commissioner says Canada isn't doing enough to fight climate change.
Image: http://media.cpac.ca/_app_images/tip_player_poster.png
Source: http://www.cpac.ca/tip-podcast/1554286033.mp3
Demo on 3v4l.org

how to translate array information into statement in php?

I am working on website that suppose to compare products. So I have reached to this following array
Array ( [iPhone 4 8GB Black] => 319 [iPhone 4S] => 449 [iphone 5] => 529 )
the key of the array is product name and the value of the array is the price. now i want to translate this array into statements like
iphone 4 8GB Black is cheapest!
iPhone 48GB Black is £130(calculation:449-319) cheaper than iphone 4S.
iPhone 48GB Black is £210(calculation:529-319) cheaper than iphone 5.
iPhone 4S is £80(calculation:529-449) cheaper than iphone 5.
iphone 5 is most expensive product from your chosen list.
Please help me on how to output those statements from an array. Your suggestion to do something else with this array in-terms of comparing would also be great. Thank you.
First, you have to sort your array with asort (in order to keep the association between your index and your values, and sort on values).
asort($yourArray);
Then, as your array is sorted, you can isolate price and names.
$names = array_keys($yourArray);
$prices = array_values($yourArray);
At this point you have 2 numerical indexed array containing your label and your prices and these 2 arrays are synchronized.
Finally, you just have to loop from 0 to the length of your array (one of them, its the same size) and made your process:
for($i = 0 ; $i < count($names) ; $i++)
{
if ($i == 0)
{
// First product -> cheapest
echo "The product " . $names[$i] . " is cheapest";
}
else if ($i == (count($names) - 1))
{
// Last product, the most expensive
echo "The product " . $names[$i] . " is the most expensive product of the list";
}
else
{
// calculate the diff between current product and first product
$diff = $price[$i] - $price[0];
echo "The product " . $names[$i] . " is " . $diff . " more expensive than " . $names[0];
}
}
This example make all comparision to the first product.
If you need all combination, it is a little more complexe, you have to make a double loop:
// Hard print the first product
echo "The product " . $names[0] . " is the cheapest";
// Make all possible comparisions
for($j = 0 ; $j < (count($names) - 1) ; $j++)
{
for($i = ($j+1) ; $i < count($names) ; $i++)
{
// calculate the diff between current product and first product
$diff = $price[$i] - $price[$j];
echo "The product " . $names[$i] . " is " . $diff . " more expensive than " . $names[$j];
}
}
// Hard print the last product
echo "The product " . $name[count($names) - 1] . " is the more expensive";

How to insert english alphabets as incremental order

Hi i have the table structure as follows
id --auto increment id
alphabet
user_id
name
and while adding i needs to insert the english alphabets to users as incremental order like this A,B,C,....Z,AA,AB,AC,...AZ,BA,BB,BC,.....BZ.
I need to get like this
id alphabet user_id name
------------------------------------------
1 A 1 name-1
2 B 1 name-2
. . . .
. . . .
26 Z 1 name-n
27 A 2 name-1
28 B 2 name-2
. . . .
. . . .
52 Z 2 name-52
53 AA 2 name-53
. . . .
. . . .
. . . .
. AZ 2 .
Thanks for your time.
It's quite easy that you use php to implement this,
please check codes below
$i = 'A';
echo $i;
echo PHP_EOL;
while($i != 'ZZ')
{
echo ++$i;
echo PHP_EOL;
}
or see the results in http://codepad.org/QB4kyV7U
Check this similar article:
Algorithm to get the excel-like column name of a number
Here's a nice simple recursive function (Based on zero indexed numbers, meaning 0 == A, 1 == B, etc)...
function getNameFromNumber($num) {
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
return getNameFromNumber($num2 - 1) . $letter;
} else {
return $letter;
}
}
And if you want it one indexed (1 == A, etc):
function getNameFromNumber($num) {
$numeric = ($num - 1) % 26;
$letter = chr(65 + $numeric);
$num2 = intval(($num - 1) / 26);
if ($num2 > 0) {
return getNameFromNumber($num2) . $letter;
} else {
return $letter;
}
}
Tested with numbers from 0 to 10000...
Sounds a lot like this SO article
MYSQL: how to "reorder" a table
Is there an absolute necessity to do what you are wanting when you can use sorting to output your data however you want?

Problems using GROUP BY in MySQL in a query that does a JOIN on two tables

I have two MySQL tables, $database1 and $database2. Both have a field in them called ID. I am passing the name of a town to the file using GET (i.e. it's in the URL of the PHP file that holds this code).
I can run this query...
$PlaceName = $_GET['townName'];
$PlaceName = mysql_real_escape_string($PlaceName);
$sql="SELECT * from $database1 LEFT JOIN $database2 on $database1.ID = $database2.ID WHERE PlaceName='$PlaceName'";
$query = mysql_query($sql);
echo '<h1>People who are searching for '.$PlaceName.':</h1>';
echo '<ul>';
while ($row = mysql_fetch_array($query)) {
echo "<li>ID #",$row['ID'],": ",$row['MemberPersonalName']," ",$row['MemberSurname']," -- searching for ",$row['SurnameBeingSearched'],"</li>";
}
echo '</ul>';
...and it works and all is well. Right now the output looks like this...
People who are searching for Hogwarts:
ID #137: Hermione Granger -- searching for Stern
ID #137: Hermione Granger -- searching for Engelberg
ID #503: Harry Potter -- searching for Kreindler
ID #549: Ron Weasley -- searching for Kreindler
ID #1062: Draco Malfoy -- searching for Engelberg
ID #1155: Ginny Weasley -- searching for Kreindler
ID #1155: Ginny Weasley -- searching for Streisand
But the output needs tweaking, and I'm having trouble writing my SQL query statement to reflect the changes. What I really want is for the output to look like this...
People who are searching for Hogwarts:
Engelberg is being searched by Hermione Granger (id #137) and Draco Malfoy (id #1062)
Kreindler is being searched by Harry Potter (id #503), Ron Weasley (id #549), and Ginny Weasley (id #1155)
Stern is being searched by Hermione Granger (id #137)
Streisand is being searched by Ginny Weasley (id #1155)
In other words, I need to group the output together by the field 'SurnameBeingSearched', I need to list the names of the people doing the searching in an "X, Y, and Z" output format (where it knows where to add a comma, if necessary, depending on the number of results), and I need to order the results by the 'SurnameBeingSearched' field.
Help? Thanks!
You need to list the names so this isn't an aggregation (in the SQL sense) problem. Keep your current query. You're going to have to do the grouping in code.
So something like:
$rows = array();
$last = '';
while ($row = mysql_fetch_array($query)) {
$surname = $row['SurnameBeingSearched'];
$id = $row['ID'];
$name = $row['MemberPersonalName'];
if ($last != $surname) {
$last = $surname;
$rows[] = array();
}
$rows[count($rows)-1][$id] = $name;
}
foreach ($rows as $row) {
// now display each group of names
}
You might also be able to use the MySQL GROUP_CONCAT() function.
It would look something like this...
SELECT places_tbl.name, GROUP_CONCAT(people_tbl.name)
FROM places_tbl
LEFT JOIN people_tbl ON (places_tbl.id = people_tbl.id)
GROUP BY places_tbl.id
GROUP_CONCAT() by default returns the values as comma delimited. You can probably split them up to get the formatting as you need it or use the SEPARATOR keyword. GROUP_CONCAT(fieldname SEPARATOR '-')
$PlaceName = $_GET['townName'];
$PlaceName = mysql_real_escape_string($PlaceName);
// note - added order to the query
$sql="SELECT * from $database1 LEFT JOIN $database2 on $database1.ID = $database2.ID WHERE PlaceName='$PlaceName'
ORDER BY SurnameBeingSearched, MemberSurname, MemberPersonalName";
$query = mysql_query($sql);
echo '<h1>People who are searching for '.$PlaceName.':</h1>';
echo '<ul>';
$cntr = mysql_num_rows($query);
if ($cntr > 0) {
$i = 0;
$srchd = mysql_result($query, $i, 'SurnameBeingSearched');
$mbr = mysql_result($query, $i, 'MemberPersonalName');
$mbr = $mbr . " " . mysql_result($query, $i, 'MemberSurname');
$mbr = $mbr . " (id #" . mysql_result($query, $i, 'ID') . ")";
$lin = $srchd . " is being searched by " . $mbr;
$prev = $srchd;
if ($cntr == 1) {
echo "<li>" . $lin . "</li>";
} else {
for ($i = 1; $i< $cntr; $i++) {
$srchd = mysql_result($query, $i, 'SurnameBeingSearched');
$mbr = mysql_result($query, $i, 'MemberPersonalName');
$mbr = $mbr . " " . mysql_result($query, $i, 'MemberSurname');
$mbr = $mbr . " (id #" . mysql_result($query, $i, 'ID') . ")";
if ($srchd == $prev) { // common search
$j = $i + 1;
if ($j < $cntr) { // still have data
$nxt = mysql_result($query, $j, 'SurnameBeingSearched');
if ($prev == $nxt) { // another one coming -- use the comma
$lin = $lin . ", " . $mbr;
} else {
$lin = $lin . ", and " . $mbr; // last member add the 'and' - line is done
echo "<li>" . $lin . "</li>";
}
$prev = $srchd;
} else { // ran out of data - need to finish the line
$lin = $lin . ", and " . $mbr; // last member add the 'and' - line is done
echo "<li>" . $lin . "</li>";
} else { // new search - need to print this line and start a new one
echo "<li>" . $lin . "</li>";
$lin = $srchd . " is being searched by " . $mbr;
$prev = $srchd;
} // test searched = previous
} // next i
} // only one row
} // cntr > 0
echo '</ul>';
/* note: this is not tested
I would recommend using table1 and table2 instead of database1 and database2
or better give the tables meaningful names
I would use active voice instead of passive voice
*/

Categories