I had a string variable in php with this value 000001422 and I used to modify it in order to display it in a better way:
<?php
$hits = "000001422";
$var = (int)$hits;
$var = abbreviateNumber($var);
echo $var; ?>
This is the function to crop and abbreviate the number in something like 1,4k
function abbreviateNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}
This worked great.
Now I'm trying to switch my code to AngularJS (I'm still learning it) so my value it's not a php variable but a scope variable received from an $http request. I have something like {{x.count}} which is my 000001422 but I would like to display it in the same way I did before.
I tryed to $hits = "{{x.count}}"; but it's not working and I think it's not the right approach. Can you address me in the right way to handle this?
EDIT:
I removed the initial zeros converting the value into an int with {{x.count - 0}} but still need to apply my abbreviate function.
Related
My first ever question on here as I'm completely stuck, so apologies if I leave out any key information - please let me know!
I am creating a PHP Battleships game and trying to use full OO. I'm really close, however, an array for one of my classes does not hold any updates I make to it.
First off, I dynamically
created a HTML table with an onclick event - which passes the coordinates to a JS function.
I then make an AJAX call in jQuery:
function shotFired(row, column) {
var coords = {
x: row,
y: column
};
$.post("data/game_controller.php", {
jsonCoords: JSON.stringify(coords)
}, function(results) {
console.log(results)
console.log(results[4])
var playerShotResult = results[0];
var computerShotX = results[1] + 1;
var computerShotY = results[2] + 1;
var computerShotResult = results[3];
var positionsClicked = document.getElementById("computer_" + row + "," + column)
switch (playerShotResult) {
case "MISS":
positionsClicked.classList.add("miss");
break;
case "HIT":
positionsClicked.classList.add("hit");
break;
case "Already Hit":
document.getElementById("outputMessage").innerHTML = result
break;
default:
console.log("Player shot defaulted");
}
}, "json")
I then use game_controller.php to handle the request and call shotFired:
<?php
session_start();
require("../classes/Game.class.php");
if (isset($_POST['jsonCoords'])) {
if (isset($_SESSION['newGame'])) {
$game = unserialize($_SESSION['newGame']);
$coords = json_decode($_POST['jsonCoords']);
$results = $game->shotFired($coords->x, $coords->y);
echo json_encode($results);
}
}
shotFired from the Game.php Class file, gets an instance of the Fleet class called computer, and runs the checkPosition function:
public function shotFired($x, $y)
{
$computer = $this->getComputer();
$playerHit = $computer->checkPosition(($x - 1), ($y - 1));
$computerGrid = $computer->getBattleshipsGrid();
$computerHit = $this->simulateComputerShot();
return [$playerHit, $computerHit[0], $computerHit[1], $computerHit[2], $computerGrid];
}
checksPosition checks the State of the Position instance in the BattleshipGrid array, and then attempts to update the array with a H or M - using a standard setter method:
public function checkPosition($x, $y): string
{
$positionObj = $this->battleshipsGrid["(" . $x . "," . $y . ")"];
$positionState = $positionObj->getState();
if ($positionState == "#") {
$positionObj->setState("M");
return "MISS";
} elseif ($positionState == "M" || $positionState == "H") {
return "Already Fired";
} else {
$positionObj->setState("H");
return "HIT";
}
}
For reference, I set the Battleships board in the constructor for Fleet.php:
// Populate associative array with instances of position
for ($y = 0; $y < $gridSize; $y++) {
for ($x = 0; $x < $gridSize; $x++) {
$coordinates = "(" . $x . "," . $y . ")";
$this->battleshipsGrid[$coordinates] = new Position($x, $y);
}
}
It works directly after it has been set - however, on the next onclick event, the H or M value is reset to it's previous value?
Seen here in console output
After a couple of hours, the closest I've come to is passing byRef in the setState function (didn't make a difference).
I've seen some notes on array_map, but I'm not sure this is what I'm looking for?
For ref, this is how I output the battleshipGrid to the console:
public function getBattleshipsGrid()
{
$readableGrid = "";
$grid = $this->battleshipsGrid;
foreach ($grid as $coordsID => $positionObj) {
$readableGrid .= "\n" . $coordsID . ": " . $positionObj->getState();
}
return $readableGrid;
}
Apologies for the long post, but I didn't want to leave anything out. Any and all help would be extremely appreciated!
Many thanks
It looks like you're not saving the state of the coordinates of the hits. If you are using the eloquent model, and setState is changing the attribute's value, make sure that you call $positionObj->save() as php does not save state on each ajax request. You will need to use a database or some sort of storage to have the server 'remember' that you clicked a specific location.
For example:
$k = "+";
$q = 8;
echo $array[$q+1];
But I want the following:
echo $array[$q$k1];
So it basically says "call the value of array which is 8+1 so 9." and if I want to call 7 I can do $k = "-".
In PHP, you can not treat operators as variables.
Still, there two basic ways you can achieve the same effect.
You can use a conditional and specify the values accordingly:
$r = 1; //the value you're adding; moved to a variable for clarity
$op = '+'; //+ means add; anything else means subtract
echo $array[$q + ($op === '+' ? $r : -$r)];
//or
if($op === '+') {
echo $array[$q + $r];
} else {
echo $array[$q - $r];
}
Or you can change the operation into a multiplication:
echo $array[$q + (($op === '+' ? 1 : -1) * $r)];
Either form will work; it's just a matter of what is most convenient for your code.
So if the last function ended up working. And I followed all of your instructions to the T, why is this function not working properly? I've looked over it for an hour, tried rewrite it over and over again and all I get is a 0 or no return.
function marketing () {
$newsold = $_POST['newsold'];
$usedsold = $_POST['usedsold'];
$carsSold = $newsold + $usedsold;
$AdSpend = $carsSold * 275;
echo "You shoud spend roughly $AdSpend per year on advertising";
}
marketing();
You echo the values inside the function:
not:
echo "$autoProfit";
but,
<?php
function autoProfits () {
$usedprofit = 1527;
$newprofit = 800;
$newsold = $_POST['newsold'];
$usedsold = $_POST['usedsold'];
$uprofit = $usedsold * $profitused;
$nprofit = $newsold * $profitnew;
$autoProfit = $uprofit + $nprofit;
}
autoProfits();
?>
Take close att with the curly brace where to be placed.
Several things with your code:
1) By default, a form will post with GET and not POST. So either change your PHP variables to $_GET OR change your form's method to $_POST. I prefer to change the method.
<form action="calc.php" method="POST">
2) You're missing a curly brace on your function:
function makeProfit () {
if ($profit >=0) {
echo "Your company is making a profit.";
} else {
echo "Your company is not making a profit.";
}
}
3) In your function adSpend(), you should invert the line for $carsSold.
4) You have used upper and lower-case characters interchangeably in your variable names ($usedSold vs $usedsold). PHP variables are case-sensitive.
5) The "+" operator when used to combine a string and integer may work, but it would be better not to put integers in quotes.
5b) Using a comma will cause PHP to not recognize your variable as a number, so use $profitUsed = 1527; instead of $profitUsed = "1,527";
6) Your variables at the top of a PHP file are not GLOBAL. You'll either need to convert them to global variables, or (I prefer) send them as parameters to your function. An example of the corrected adSpend():
function adSpend ($newSold = 0, $usedSold = 0) {
$adSpendPerCar = 275;
$carsSold = $newSold + $usedSold;
$adSpend = $carsSold * $adSpendPerCar;
echo $AdSpend;
}
adSpend($newSold, $usedSold);
7) Finally, when you expect an integer from user input, you'd be best to verify that you have an integer. There are a lot of ways to do this, one simple method is to do something like this:
$newSold = intval($_POST['newsold']);
$usedSold = intval($_POST['usedsold']);
Edit Change your variables $profitused for $usedprofit and $profitnew for $newprofit
function autoProfits () {
$usedprofit = 1527;
$newprofit = 800;
$newsold = $_POST['newsold'];
$usedsold = $_POST['usedsold'];
$uprofit = $usedsold * $usedprofit;
$nprofit = $newsold * $newprofit;
$autoProfit = $uprofit + $nprofit;
echo $autoProfit;
}
function makeProfit () {
if ($profit >=0) {
echo "Your company is making a profit.";
} else {
echo "Your company is not making a profit.";
}
}
This function is missing the last '}' (curly bracket)
But you should also be sure when calling adSpend(), that the variables you're trying to access is set, else you won't get anything out of it.
Since you've made that setup, then you should be calling the functions right after you've set all the variables, for anything to work.
You're using undefined variables on the products. You defined $usedprofit and $newprofit but you're multiplying $profitused and $profitnew. Since they're not defined, PHP assumes they're 0.
Assume the following variable values were set earlier in the code:
LSLATHOR = 1780, NRSLATVER = 34
Then I have these two lines of GWBASIC:
100 PITCHHOR=(LSLATHOR/(NRSLATVER+1)) : LSLATHOR=PITCHHOR*(NRSLATVER+1)
110 IF PITCHHOR>72 THEN NRSLATVER=NRSLATVER+1:GOTO 100
120 LPRINT "HORIZONTAL PITCH is equal to : ";PITCHHOR;
Now if I wanted to put this logic as a PHP function how would I go about it?:
function calc_h($slat_length_h, $slat_qty_v) {
$pitch_h = ($slat_length_h / ($v_slat_qty + 1));
if ($pitch_h > 72) {
while ($pitch_h > 72) {
$v_slat_qty += 1;
$slat_length_h = $pitch_h * ($v_slat_qty + 1);
$pitch_h = ($slat_length_h / ($v_slat_qty + 1));
}
}
return $pitch_h;
}
$slat_length_h = 1780;
$slat_qty_v = 34;
echo calc_h($slat_length_h, $slat_qty_v);
What you need to know is that a condition will sometimes exist where PITCHHOR > 72 then it needs to adjust/re-calculate the $pitch_h according to the GWBasic script.
I hope I provided enough info. Ty vm.
I'd write as follows. But since you have the original code, you can simply try to plug in a few sample values and compare the results.
function calc_pitchhor($lslathor, $nrslatver) {
do {
$pitchhor = ($lslathor/($nrslatver+1));
$lslathor = $pitchhor*($nrslatver+1);
++$nrslatver;
} while($pitchhor > 72)
return $pitchhor;
}
$lslathor = 1780;
$nrslatver = 34;
echo "HORIZONTAL PITCH is equal to: ", calc_pitchhor($slat_length_h, $slat_qty_v);
I'm trying to convert the LZW decompressor from JSend which is in php to javascript, and I've gotten to a function I can't quite make sense of.
private static function decompressLZW($aCodes)
{
$sData = '';
$oDictionary = range("\x0000", "\xff");
foreach ($aCodes as $sKey => $iCode)
{
$sElement = $oDictionary[$iCode];
if (!isset($sElement))
$sElement = $sWord . $sWord[0];
$sData .= $sElement;
if ($sKey)
$oDictionary[] = $sWord . $sElement[0];
$sWord = $sElement;
}
return $sData;
}
This is what I have in javascript so far, but I when I run this in javascript, it complains that sWord isn't defined and looking at the php function, I don't see how this doesn't produce an error?
Here's what I have in javscript so far:
function decompressLZW(aCodes) {
var sData = '';
var oDictionary = [];
for (var i = 0; i < 256; i++) {
oDictionary[String.fromCharCode(i)] = i;
}
for(var i=0, iLn = aCodes.length; i < iLn; i++) {
var sElement = oDictionary[aCodes[i]];
if(!sElement) {
sElement = sWord + sWord[0];
}
//some magic needs to happen here
}
return sData;
}
Well its kind of bad IMO but.... $sWord is essentially $sElement which is defined near the end of the iteration. They are counting on the first two if statements be true only after the at least a single run of the loop in which case $sWord would be the same as the previous iteration's $sElement.
Im not sure what the significance of that assumption is but if it were me i would still test for the existence of $sWord and throw an exception if that happened (even if it should theoretically never happen)...
So you need to figure out why sElement = oDictionary[aCodes[i]]; isnt evaluating to something truthy. It may be as simple as testing angainst undefined (which is more like doing isset()) instead of doing loose falsy check.
if(sElement === undefined) {
sElement = sWord + sWord[0];
}