Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Take these levels:
level1 = 0days
level2 = 30days
level3 = 90days
All these levels are totally dynamic. Admin can alter number of levels and duration of levels at any time.
I am recording numberOfDailyLogin in a series, so if user not login even for 1 day meter reset to 0.
I am trying to give user a special level tag on basis of numberOfDailyLogin
I have a solution already by running a while loop from 0 to numberOfDailyLogin and update variable once >= daysRequired for login.
But I don't want it this way, want something easy
I am totally clueless at this point, I can't hardcode any of the
value, so please if you are interest please give some suggestion.
#Edit1
// json response for levels
{
"status": 200,
"body": [
{
"name": "level1",
"after_days": 0,
},
{
"name": "level2",
"after_days": 50,
},
{
"name": "level3",
"after_days": 180,
}
]
}
function getLevel($allLevels, $numberOfDailyLogins) {
foreach ($allLevels as $l) {
if ($numberOfDailyLogins > $l['after_days']) {
return $l['name'];
}
}
}
Problem is if numberOfDailyLogins=51.. so it should show level2... cause after 50 days userLevel reached to level2.. but my code return level1 which is totally wrong.
#brombeer suggestion works for me, Thanks mate
function getLevel($allLevels, $numberOfDailyLogins) {
$level = null;
foreach ($allLevels as $l) {
if ($numberOfDailyLogins> $l['after_days']) {
$level = $l;
}
}
// TO-DO... do whatever you want
}
It's a simple logic error - your code returns after the first iteration because the value is already greater than 0 (the first level in the list).
One simple solution is to search the array in reverse instead:
function getLevel($allLevels, $numberOfDailyLogins) {
for ($i = count($allLevels) -1; $i >= 0; $i--) {
if ($numberOfDailyLogins > $allLevels[$i]['after_days']) {
return $allLevels[$i]['name'];
}
}
}
Demo: http://sandbox.onlinephpfunctions.com/code/3b00c6d182676411915cae1fbb21a1afba2548e8
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
My API call returns the following JSON output before json_decode:
{
"projects": [
{
"project_id": 00000001,
"name": "A title",
"price": "0.99",
"country": "US",
"platform_types": [
"android_phone",
"ios_phone",
"ios_tablet",
"android_kindle",
"android_tablet",
"desktop"
],
"comment": "A text of a comment"
}
{
"project_id": 00000002,
"name": "Another title",
"price": "1.03",
"country": "US",
"platform_types": [
"android_phone",
"ios_phone",
"ios_tablet",
"android_kindle",
"android_tablet",
"desktop"
],
"comment": "Another text of a comment"
}
]
}
The following code parses the multi-level json and shows the whole projects list:
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
foreach($result['projects'] as $project) {
$project_id = $project['project_id'];
$name = $project['name'];
$price = $project['price'];
$country = $project['country'];
#no values for the fields, that's why commented
#$android_phone = $project['platform_types']['android_phone'];
#$ios_phone = $project['platform_types']['ios_phone'];
#$ios_tablet = $project['platform_types']['ios_tablet'];
#$android_kindle = $project['platform_types']['android_kindle'];
#$android_tablet = $project['platform_types']['android_tablet'];
#$desktop = $project['platform_types']['desktop'];
$comment = $project['comment'];
echo $project_id,'<br>',$name,'<br>',$price,'<br>',$country,'<br>',$comment,'<br>';
}
I got the following output:
00000001
A title
0.99
US
A text of a comment
00000002
Another title
1.03
US
Another text of a comment
The questions are:
How to list available device types (the fields have names only and no values)?
How to filter the array based on certain criteria (price must be equal or higher $1.00)?
How to filter elements based on fields without values (show projects just for Android devices)?
Question 1
to list all the available device types per project as a json you should access it's corresponding tree
foreach($result['projects'] as $project) {
$project_device_types = $project['plateform_type'];
echo '<pre>'.$project_device_types.'<pre>';
}
Question 2
to filter the array use [array_filter][1] in
$filtered = array_filter($result['projects'], function($project) {
if($project['price'] >= 90) {
return true
}
});
// use it instead of the $result variable
foreach($filtered as $project) {
$project_id = $project['project_id'];
$name = $project['name'];
$price = $project['price'];
}
Question 3
you can follow the exact pattern as the second question and that is by using array_filter so eg. let's say you want only the android devices
array_filter($result['projects'], function($project) {
if(in_array($project['platform_types'], "Android")) { // check if the plateform type include android by using [in_array][1]
return true
}
});
NB: in_array is case sensitive so make sure that the capitalization is correct
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code was made by other, but i want to change it for my own purposes.
The code is giving 13 numbers, but only want the numbers of the ID(from database).
Example of what i need:
ID = 908
EAN13 = 000000908
My real question is how can i remove the 0000 from the BARS, then after scanning the SCANNER wil read the correct ID.
This is fora study guys!
class PDF_BARCODE extends FPDF
{
function EAN13($x, $y, $barcode, $h=16, $w=.35, $fSize=9)
{
$this->Barcode($x,$y,$barcode,$h,$w,$fSize,13);
}
function UPC_A($x, $y, $barcode, $h=16, $w=.35, $fSize=9)
{
$this->Barcode($x,$y,$barcode,$h,$w,$fSize,12);
}
function GetCheckDigit($barcode)
{
//Compute the check digit
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode[$i];
for($i=0;$i<=10;$i+=2)
$sum+=$barcode[$i];
$r=$sum%10;
if($r>0)
$r=10-$r;
return $r;
}
function TestCheckDigit($barcode)
{
//Test validity of check digit
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode[$i];
for($i=0;$i<=10;$i+=2)
$sum+=$barcode[$i];
return ($sum+$barcode[12])%10==0;
}
function Barcode($x, $y, $barcode, $h, $w, $fSize, $len)
{
//Padding
$barcode=str_pad($barcode,$len-1,'0',STR_PAD_LEFT);
if($len==12)
$barcode='0'.$barcode;
//Add or control the check digit
if(strlen($barcode)==12)
$barcode.=$this->GetCheckDigit($barcode);
elseif(!$this->TestCheckDigit($barcode))
$this->Error('Incorrect check digit');
//Convert digits to bars
$codes=array(
'A'=>array(
'0'=>'0001101','1'=>'0011001','2'=>'0010011','3'=>'0111101','4'=>'0100011',
'5'=>'0110001','6'=>'0101111','7'=>'0111011','8'=>'0110111','9'=>'0001011'),
'B'=>array(
'0'=>'0100111','1'=>'0110011','2'=>'0011011','3'=>'0100001','4'=>'0011101',
'5'=>'0111001','6'=>'0000101','7'=>'0010001','8'=>'0001001','9'=>'0010111'),
'C'=>array(
'0'=>'1110010','1'=>'1100110','2'=>'1101100','3'=>'1000010','4'=>'1011100',
'5'=>'1001110','6'=>'1010000','7'=>'1000100','8'=>'1001000','9'=>'1110100')
);
$parities=array(
'0'=>array('A','A','A','A','A','A'),
'1'=>array('A','A','B','A','B','B'),
'2'=>array('A','A','B','B','A','B'),
'3'=>array('A','A','B','B','B','A'),
'4'=>array('A','B','A','A','B','B'),
'5'=>array('A','B','B','A','A','B'),
'6'=>array('A','B','B','B','A','A'),
'7'=>array('A','B','A','B','A','B'),
'8'=>array('A','B','A','B','B','A'),
'9'=>array('A','B','B','A','B','A')
);
$code='101';
$p=$parities[$barcode[0]];
for($i=1;$i<=6;$i++)
$code.=$codes[$p[$i-1]][$barcode[$i]];
$code.='01010';
for($i=7;$i<=12;$i++)
$code.=$codes['C'][$barcode[$i]];
$code.='101';
//Draw bars
for($i=0;$i<strlen($code);$i++)
{
if($code[$i]=='1')
$this->Rect($x+$i*$w,$y,$w,$h,'F');
}
//Print text uder barcode
$this->SetFont('Arial','',$fSize);
$this->Text($x,$y+$h+11/$this->k,substr($barcode,-$len));
}
}
The EAN-13 barcode format inherently encodes 13 digits. If you mess with it so it encodes fewer digits, the barcode will no longer be EAN-13, and many barcode readers will not recognize it.
You're using leading zeros on your codes in your nonstandard application. I say nonstandard because EAN-13 has a registry of prefixes. Whatever you use to read your barcodes will need to remove the leading zeros.
If you must avoid leading zeros in your barcode, you may want to switch to another more flexible barcode format, Code 39, Codabar, or even QR codes. Or you might choose EAN-8 or EAN-5. You can look up all these.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm learning about functions in my programming class and no matter what I do I just cant get this to work. Here is the problem that needs fixing:
What's wrong here?
The getWage() function is supposed to calculate overtime (time and a half) for any hours worked above 40. The function is working just fine but when we send the $hoursWorked and $hourlyWage from THIS program the function does not calculate the overtime as time and a half!
Can you fix it? The wage should be $605.63 not $573.75
Here is my function:
<?php
function getWage($hourlyWage, $hoursWorked) {
if ($hoursWorked <= 40)
return round(($hourlyWage * $hoursWorked), 2);
else
return round((($hourlyWage * 40) +
($hourlyWage * 1.5 * ($hoursWorked - 40))), 2);
}
?>
and here is where I try to call it to my program:
<?php
include("incWageFunctions.php");
$hourlyWage = 12.75;
$hoursWorked = 45;
$wage = getWage($hoursWorked, $hourlyWage);
print("<p>Your hourly wage is $$hourlyWage and you worked
$hoursWorked hours.</p>");
print("<p>Your wages are $$wage.</p>");
?>
Its not calculating the overtime no matter what... Where am I going wrong?! Also, how would you call multiple functions to the same program to calculate different things? Can I just call it with the name after the include statement? Or do I have to have it written out with the { } like my first function in this question??
You interchanged $hoursWorked and $hourlyWage
Change $wage = getWage($hoursWorked, $hourlyWage);
To $wage = getWage($hourlyWage, $hoursWorked);
You have mixed up the arguments. In php-file you have coded:
$wage = getWage($hoursWorked, $hourlyWage);
However, in incWageFunctions.php you have written:
function getWage($hourlyWage, $hoursWorked)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I've a bit trouble with "foreach". The test page displays:
*Warning: Invalid argument supplied for foreach() in /data/web/virtuals/23481/virtual/www/subdom/vsohbrno/poi/junaio/junaio/test.php on line 60*
*Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag in /data/web/virtuals/23481/virtual/www/subdom/vsohbrno/poi/junaio/junaio/test.php on line 64*
*Warning: Invalid argument supplied for foreach() in /data/web/virtuals/23481/virtual/www/subdom/vsohbrno/poi/junaio/junaio/test.php on line 68*
However I make it for Junaio (AR application for smartphone) - and when I tried to run it here (in the app), I had no trouble with it - it's working. But if the warnings will be disappear also in www pages, it would be fine =o)
My source code:
<?php
require_once '../ARELLibrary/arel_xmlhelper.class.php';
if(!empty($_GET['l']))
$position = explode(",", $_GET['l']);
else
trigger_error("user position (l) missing. For testing, please provide a 'l' GET parameter with your request. e.g. pois/search/?l=23.34534,11.56734,0");
//create the xml start
ArelXMLHelper::start(NULL, "/arel/index.html");
//start by defining some positions of geo referenced POIs and give those names and thumbnails
$treasureLocations = array(
array("48.6045911000,14.7007322000,0", "Tradiční výroba marmelád a povidel ", "Jih Čech > Šumava > Šumava a Pošumaví. Obec: Pohorská Ves."),
array("48.6438239000,14.2208661000,0", "Restaurace Czech Specials (Restaurace Lanovka)", "Jih Čech > Šumava > Šumava a Pošumaví. Obec: Lipno nad Vltavou."),
array("48.6541914000,14.0354000000,0", "Plavení dřeva, vorařství – Schwarzenberský plavební kanál", "Jih Čech > Šumava > Šumava a Pošumaví. Obec: Přední Výtoň."),
);
//in the filter_value, the continent parameter will be send from the client, once the continent is filtered
$filter = $_GET['filter_value'];
//display the POIs as defined in the Constructor
$countpoi = 1;
foreach($treasureLocations as $i => $findPOI)
{
//Parameters for distance calculate. $Location = GPS coordinates of the POI, $Position = my GPS position.
$location = explode(",", $findPOI[0]);
//Calculate distance beween my position and POI
$deg2RadNumber = (float)(pi() / 180);
$earthRadius= 6371.009;
$latitudeDistance=((float)$position[0]-(float)$location[0])*$deg2RadNumber;
$longitudeDistance=((float)$position[1]-(float)$location[1])*$deg2RadNumber;
$a=pow(sin($latitudeDistance/2.0),2) + cos((float)$position[0]*$deg2RadNumber) * cos((float)$location[0]*$deg2RadNumber) * pow(sin($longitudeDistance/2.0),2);
$c=2.0*atan2(sqrt($a),sqrt(1.0- $a));
$distance=round($earthRadius*$c);
//Set distance for displaying objects (in kilometers)
if($distance < 10)
{
$title = $findPOI[1]; //Title of the POI
$poi[$countpoi]['attribution'] = $findPOI[2]; //Description of the POI
$poi[$countpoi]['distance'] = $distance; // Distance between POI and me
//create the POI
$poi[$countpoi]['poi'] = ArelXMLHelper::createLocationBasedPOI($i, $title, explode(",", $findPOI[0]), "http://vsohbrno.chudst.cz/poi/poi_obrazek.png", "http://vsohbrno.chudst.cz/poi/poi_obrazek.png", $poi[$countpoi]['attribution'], NULL);
$countpoi++;
}
}
//Sorting POI (the closest -> the furthest)
foreach ($poi as $val)
{
$sortarray[] = $val['distance'];
}
array_multisort($sortarray,$poi);
//Write 39 POI to XML file
foreach ($poi as $POInumber => $POIvalue)
{
if($POInumber < 39){
if(!empty($filter))
{
if(strtolower($filter) == strtolower($poi[$POInumber]['attribution']))
{
ArelXMLHelper::outputObject($poi[$POInumber]['poi']);
}
}
else
{ArelXMLHelper::outputObject($poi[$POInumber]['poi']);}
}
}
//end the output
ArelXMLHelper::end();
?>
If the distance is never smaller than 10 km, $poi will not be initialised, which is what the error means.
Initialise $poi to be an array and it should remove the warnings:
$poi = array();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I saw on StackOverflow a "point in polygon" raytracing algorithm that I implemented in my PHP Code. Most of the time, it works well, but in some complicated cases, with complex polygons and vicious points, it fails and it says that point in not in polygon when it is.
For example:
You will find here my Polygon and Point classes: pointInPolygon method is in Polygon class. At the end of the file, there are two points that are supposed to lie inside the given polygon (True on Google Earth). The second one works well, but the first one is buggy :( .
You can easily check the polygon on Google Earth using this KML file.
Have been there :-) I also travelled through Stackoverflow's PiP-suggestions, including your reference and this thread. Unfortunately, none of the suggestions (at least those I tried) were flawless and sufficient for a real-life scenario: like users plotting complex polygons on a Google map in freehand, "vicious" right vs left issues, negative numbers and so on.
The PiP-algorithm must work in all cases, even if the polygon consists of hundreds of thousands of points (like a county-border, nature park and so on) - no matter how "crazy" the polygon is.
So I ended up building a new algorithm, based on some source from an astronomy-app:
//Point class, storage of lat/long-pairs
class Point {
public $lat;
public $long;
function Point($lat, $long) {
$this->lat = $lat;
$this->long = $long;
}
}
//the Point in Polygon function
function pointInPolygon($p, $polygon) {
//if you operates with (hundred)thousands of points
set_time_limit(60);
$c = 0;
$p1 = $polygon[0];
$n = count($polygon);
for ($i=1; $i<=$n; $i++) {
$p2 = $polygon[$i % $n];
if ($p->long > min($p1->long, $p2->long)
&& $p->long <= max($p1->long, $p2->long)
&& $p->lat <= max($p1->lat, $p2->lat)
&& $p1->long != $p2->long) {
$xinters = ($p->long - $p1->long) * ($p2->lat - $p1->lat) / ($p2->long - $p1->long) + $p1->lat;
if ($p1->lat == $p2->lat || $p->lat <= $xinters) {
$c++;
}
}
$p1 = $p2;
}
// if the number of edges we passed through is even, then it's not in the poly.
return $c%2!=0;
}
Illustrative test :
$polygon = array(
new Point(1,1),
new Point(1,4),
new Point(4,4),
new Point(4,1)
);
function test($lat, $long) {
global $polygon;
$ll=$lat.','.$long;
echo (pointInPolygon(new Point($lat,$long), $polygon)) ? $ll .' is inside polygon<br>' : $ll.' is outside<br>';
}
test(2, 2);
test(1, 1);
test(1.5333, 2.3434);
test(400, -100);
test(1.01, 1.01);
Outputs :
2,2 is inside polygon
1,1 is outside
1.5333,2.3434 is inside polygon
400,-100 is outside
1.01,1.01 is inside polygon
It is now more than a year since I switched to the above algorithm on several sites. Unlike the "SO-algorithms" there have not been any complaints so far. See it in action here (national mycological database, sorry for the Danish). You can plot a polygon, or select a "kommune" (a county) - ultimately compare a polygon with thousands of points to thousands of records).
Update
Note, this algorithm is targeting geodata / lat,lngs which can be very precise (n'th decimal), therefore considering "in polygon" as inside polygon - not on border of polygon. 1,1 is considered outside, since it is on the border. 1.0000000001,1.01 is not.