I have mock fantasy football form that creates data in an external text file and I have everything working, I have just run into one problem. Can someone show me how I can sort the players by their number (largest on top) and then highlight (in red) the whole row of the player that has had the most points?
Here is my form file:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>Fantasy Football</title>
</head>
<body>
<form action="team.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Position</td><td><input type="text" name="position"</td></tr>
<tr><td>Number</td><td><input type="text" name="number"</td></tr>
<tr><td>Team</td><td><input type="text" name="team"</td></tr>
<tr><td>Points per game</td><td><input type="text" name="points"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
And here is the return data:
<?php
$name = $_POST['name'];
$team = $_POST['team'];
$number = $_POST['number'];
$position = $_POST['position'];
$points = $_POST['points'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../php/football.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$team."|".$number."|".$position."|".$points."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../php/football.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Team</td> <td>number</td> <td>Position</td> <td>Points</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$team.'</td><td>'.$number.'</td>
<td>'.$position.'</td><td>'.$points.'</td></tr>';
}
echo '</table>';
?>
Not really good at inserting bits an pieces of code, so if you could, can you tell me exactly where to put whatever you can give me?
Update:
Is this where I needed to put everything? The way it is now, when I submit my form I don't see anything! Obviously I did something wrong, so I'm open to suggestions!
<?php
function sort_player_array( $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
?>
<?php
$name = $_POST['name'];
$team = $_POST['team'];
$number = $_POST['number'];
$position = $_POST['position'];
$points = $_POST['points'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../php/football.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
?>
<?php
fwrite($fp, $name."|".$team."|".$number."|".$position."|".$points."\n");
$players = file("$DOC_ROOT/../php/football.txt");
$player_array = array();
foreach($players AS $player)
{
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
$player_array[] = array('name' => $name,
'number' => $number,
'position' => $position,
'points' => $points,
);
}
$sorted_players = sort_player_array($player_array, 'number', true);
foreach( $sorted_players AS $player )
{
echo '<tr><td>'.$player[name].'</td><td>'.$player[team].'</td><td>'
.$player[number].'</td><td>'.$player[position].'</td><td>'.$player[points].'</td></tr>';
} ?>
first of all you are programming in PHP, use COUNT() instead of SIZEOF().
sizeof() is an alias of count() and might be removed as php evolves.
We need a function for sorting the array:
function sort_player_array( $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
next build an array with php holding your data, then sort it .
$players = file("$DOC_ROOT/../php/football.txt");
$player_array = array();
foreach($players AS $player)
{
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
$player_array[] = array('name' => $name,
'number' => $number,
'position' => $position,
'points' => $points,
);
}
We sort the array as you requested by number, but any key is possible. also you can set ASC or DESC with the third variable
$sorted_players = sort_player_array($player_array, 'number', true);
foreach( $sorted_players AS $player )
{
echo '<tr><td>'.$player[name].'</td><td>'.$player[team].'</td><td>'.$player[number].'</td><td>'.$player[position].'</td><td>'.$player[points].'</td></tr>';
}
Seems like you need some kind of sorting algorithm function for $players. There are different kinds, and you can find many by googling "sorting algorithms", or you can write one yourself if you feel like "reinventing the wheel". Doing one yourself does make for good practice/fun :D
Here's a link to a wiki on bubble sort, probably the most common basic sorting and would help in your situation.
Prepare an array $playerData, which contains all player records and use their numbers as key. Then use ksort():
ksort( $playerData );
While preparing the $playerData, keep a variable $maxPoints and $mapPointsPlayerNumber and check each player's data against these values. Update them if current player's point is higher than $maxPoints.
I think you should be able to create arrays with the list function. Something like this:
//set array variables
for($i = 0; $i < sizeof($players); $i++) {
list($name[],$team[],$number[],$position[],$points[]) = explode('|', $players[$i]);
}
//sort all arrays by the number, in descending order
array_multisort($number, $position, $name, $team, $points, SORT_DESC);
//set the highest points to mostPoints variable
var mostPoints = max($points);
//Output table rows
for($i = 0; $i < sizeof($players); $i++) {
if($points[$i]==mostPoints){
//red background
echo '<tr style="background:#F44">';
}else{
echo '<tr>';
}
echo '<td>'.$name[$i].'</td><td>'.$team[$i].'</td><td>'.$number[$i].'</td><td>'.$position[$i].'</td><td>'.$points[$i].'</td></tr>';
}
I haven't tested this, so there may be a few things in there that I've missed, but it should work. See Array Multisort, and max functions. It may be better to assign a class to the red table row, instead of a style; that way you can alter the td tags; I think that's more browser-friendly. The CSS for that would be something like .redRow td {background:#F44} if you gave the tr the redRow class.
Related
My objective is to create a multidimensional associative array with friends and their dreams (user input) in it. I think (hope) that I can am close to finishing it, but I get an unwanted result when echoing the final step:
I am trying to echo a sentence including the name of a 'friend' on line 22. Instead of a name inputted by the user, I get 'Array' as a result. E.g.: Array has this as their dream: Climbing Mount Everest
Does anyone know how I get the name of the friend here?
A line/string should be echoed for every separate dream that was filled in. And I included the print function for my clarity, will delete later. Thanks!
<?php
$friends = readline('How many friends should we ask for their dreams? ');
$array = [];
if (is_numeric($friends) == false) {
exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
exit("This is not valid input." . PHP_EOL);
} else {
for ($i = 1; $i <= $friends; $i++) {
$name_key = readline('What is your name? ');
$number_dreams = readline('How many dreams are you going to enter? ');
for ($x = 1; $x <= $number_dreams; $x++) {
$dream_value = readline('What is your dream? ');
$array[$name_key][] = $dream_value;
}
print_r($array);
}
foreach ($array as $friend) {
foreach ($friend as $key => $value) {
echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
}
}
}
try this after you assembled $array:
foreach ($array as $frndNm=>$dreams){
foreach($dreams as $dream){
echo( $frndNm.' dream is '.$dream);
}
}
Newly-entered products are displayed in the last row. If there is a large amount, it is difficult to see at the bottom. How can I change the new display to the top. Thank you!
$barcodes_ary = explode(',', $barcodes);
$barcodes_hash = array ();
foreach ($barcodes_ary as $b) {
if (array_key_exists($b, $barcodes_hash)) {
$barcodes_hash[$b] += 1;
} else {
$barcodes_hash[$b] = 1;
}
}
foreach ($barcodes_hash as $b => $amount) {
if ($barcodes_ary == array(''))continue;
$ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName");
if ( count($ary) == 0 ) {
continue;
}
$pid = $ary[0]['ProductID'];
$pn = $ary[0]['ProductName'];
$unit = $ary[0]['UnitID'];
$ary2 = get_sql("SELECT UnitName FROM Units WHERE UnitID = '$unit'");
$unit = $ary2[0]['UnitName'];
?>
<TR>
<TD><? echo "$pn"; ?></TD>
<TD>
<INPUT TYPE=hidden NAME=productid<?=$pid?> VALUE='<?=$pid?>'>
<?
$candidates = array();
for($i=1; $i <= DropDownMaxValue; $i++) {
$candidates[]=$i;
}
//update
I use another way to solve the problem. Just display the same product.
function push_barcode() {
// alert('barcode pushing');
b = document.form1.barcode;
bs = document.form1.barcodes;
if (bs.value == "") {
bs.value = b.value;
} else { // ?? 111,333,444,... ???
bs.value = b.value;
}
}
Okay, you should be able to get the count using the keys values returned in reverse in brackets with the array.
Try the following and see if it works for you...
$ProductName = $ary[0]['ProductName'];
//--> get the count of your array
$count = count($ProductName);
//--> define an output variable to hold values
$output = null;
$i = 0;
//--> reduce count by one as key values start at 0 and count starts at 1
$count = $count - 1;
//--> subtraction and addition of $count by one to reduce warning
//--> of `undefined offset` for index on mismatched key values
while($count + 1){
//--> concatenate the values into a variable for display
$output .= $ProductName[$count];
//--> or push the reversed values back into an array
$product_name[$i] = $ProductName[$count];
//--> $product_name should now hold your values in reverse use a foreach
// use a foreach to display values in your table
$count--;
$i++;
}
I want to calculate and show the turnover of some webshops(Plattform:Shopware), filtered by month and without canceled orders.
I got the connection to the webshop, I already got all orders, sorted them by month, filtered out the canceled orders. Now I pushed all relevant orders into a new array called $october. In $october, every single order is an array itself with many keys and values. I just need to summarize all "invoiceAmount" values together so i can show the turnover of this month. I tried many variations(commented), the best i get is "0" from the initialization of $sum... but im also very new to php. please help me out :-)
API Resources Orders
<?php
include_once ('api.php');
$url = xxxxx;
$user = xxxxx;
$key = xxxxx;
$client = new ApiClient($url,$user,$key);
$orders = $client->get('orders');
$october = [];
echo "<h1>===================month Array==============</h1>";
foreach ($orders as $order) {
foreach ($order as $field) {
if ($field["orderStatusId"]!==4) {
$mystring = $field[orderTime];
$findme = '-10-';
$pos = strpos($mystring, $findme);
if ($pos !=null) {
print_r($field);
array_push($october,$field);
}
}
}
}
echo "<script>";
echo 'console.log('.json_encode($october).')';
echo "</script>";
print_r($october);
echo("<h1>===================Sum of month==============</h1>");
$sumOctober = 0;
foreach ($october as $field["invoiceAmount"]=>$value) {
$sumOctober+= $value;
}
/*
$sumOctober = 0;
foreach ($october as $order) {
foreach ($order as $field["invoiceAmount"]=>$value) {
$sumOctober+= $value;
}
}
*/
echo($sumOctober);
/*
$arr = $october;
$sum = 0;
foreach ($arr as $order){
foreach ($order as $field["invoiceAmount"]=>$value) {
$sum += $value;
}
}
*/
/*
$arr = $october($orders($key));
$sum = 0;
array_walk_recursive($arr, function($val, $key) use (&$sum) {
$sum += $val;
});
var_dump($sum);
echo "<h1>Die Summe Oktober ist:</h1>";
echo ($sum);
*/
?>
This totally helped, dont know why the guy deleted his answer right away...but thanks!
$sumOctober = 0;
foreach ($october as $oct) {
$sumOctober+= $oct["invoiceAmount"];
}
I couldn't understand the multidimensional array in PHP properly. I have a CSV file having two columns as shown below:
I am trying to create an array of array, in which each key is a cataegory. However, the value of each key is an array. In this array, each key is company and value is the count of the product. See below the code:
<?php
//array contains value
function contains_value($my_array, $value_search){
foreach ($my_array as $key => $value) {
if ($value === $value_search)
return true;
}
return false;
}
//array contains key
function contains_key($my_array, $key_search){
foreach ($my_array as $key => $value) {
if ($key === $key_search)
return true;
}
return false;
}
$handle = fopen("product_list.csv", "r");
$products = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
$product = explode(",", $line);
$category = $product[0];
$company = $product[1];
if (contains_key($products, $category)) {
if (contains_value($products, $company)) {
//increase the count of category by 1
$products[$category][$company] = $products[$category][$company] + 1;
} else {
//append new company with count 1
array_push($products[$category], array(
$company,
1
));
}
} else {
//initialize new company with count 1
$products[$category] = array(
$company,
1
);
}
}
fclose($handle);
}
var_dump($products);
?>
I noticed that the var_dump($products) is not showing correction information. I am expecting following kind of result:
I haven't enough reputation to reply, but I think he need counts.
To complete the answer of Alive to Die, more something like this:
if (!array_key_exists($category, $products)) {
products[$category] = [];
}
if (!array_key_exists($company, $products[$category])) {
products[$category][$company] = 0;
}
++$results[$cataegory][$company];
But cleaner ;)
Edit:
If I remember well, his first idea was this:
$products[$category][] = $company;
The code is shorter. Maybe you can combine the two ideas.
For example:
$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.
Here's my attempt:
<?php
$arr = array(3,5,2,5,3,9);
$temp_array = array();
foreach($arr as $val)
{
if(isset($temp_array[$val]))
{
$temp_array[$val] = $val;
}else{
$temp_array[$val] = 0;
}
}
foreach($temp_array as $val2)
{
if($val2 > 0)
{
echo $val2 . ', ';
}
}
?>
--
Output --
3, 5,
Try the following:
$arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset($arr[$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array($val,$arr)){
echo $val . " ";
}
}
Output:
3 5
Addition:
I guess that the reason you were asked to implement it yourself (without using built-in functions) was to avoid answers like:
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
$arrnew = array();
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($arr[$i]==$arr[$j])
{
$arrnew[]=$arr[$j];
}
}
}