Convert array result into integer for calculating - php

I have a little problem with an array.
I have an array which looks like this:
Array
(
[start] => Array
(
[0] => 15168
)
[ende] => Array
(
[0] => 43
)
[string] => Array
(
[0] => 1050
)
)
The number I need is 1050. So I get it like this:
$number = $tabelle['string'][0];
Now my problem is that I can't use it in calculations. I already tried to convert it into an integer with the following line:
$number = intval($tabelle['string'][0]);
But this doesn't work. I always get 0 for $number. How to do it properly? I already searched on Google for about 2 hours.
Best regards
My whole script:
<?php
class data_pars {
var $datei;
var $read_laenge = 2000;
var $result;
function set_datei($datei) {
$this->datei = $datei;
}
function read($start,$ende) {
$file = #fopen ($this->datei,"r");
while (!feof($file)) {
$inhalt .= fgets($file,$this->read_laenge);
}
if(!$start) $start = 0;
if(!$ende) $ende = strlen($inhalt);
if($ende > strlen($inhalt)) $ende = strlen($inhalt);
$this->result = substr($inhalt,$start,$ende);
}
function get_result() {
return $this->result;
}
function get_in_out($in,$out,$in_out) {
$anzahl_ende = strlen($out);
$anzahl_start = strlen($in);
$start = 0;
$anzahl = substr_count($this->result, $in);
$count = 0;
if(!$in_out) {
$ad_start = $anzahl_start;
$ad_ende = $anzahl_ende;
}
while($count < $anzahl) {
$ar_start = strpos($this->result, $in, $start);
$ar_ende = strpos($this->result, $out, $ar_start + $anzahl_start);
$ar_string = substr($this->result,$ar_start + $ad_start, $ar_ende - $ar_start + $anzahl_ende - $ad_ende - $ad_start);
$output[start][] = $ar_start;
$output[ende][] = $ar_ende - $ar_start + $anzahl_ende;
$output[string][] = trim($ar_string);
$start = $ar_start + $anzahl_start;
$count++;
}
return $output;
}
}
$data = new data_pars();
$data->set_datei('http://www.elitepvpers.com/theblackmarket/profile/6005376');
$data->read('0','20000');
$tabelle = $data->get_in_out('<td>elite*gold:</td>','</td>',false);
$number = intval($tabelle['string'][0]);
echo '<pre>';
print_r($tabelle);
echo '</pre>';
echo $number;
?>
So I always get 0 for $number instead of 1050;

You did 2 main errors:
1. You have to initialize $inhalt before your while loop like this:
$inhalt = "";
while (!feof($file)) {
$inhalt .= fgets($file,$this->read_laenge);
}
2. You forgot to put quotes around the indexes:
$output["start"][] = $ar_start;
$output["ende"][] = $ar_ende - $ar_start + $anzahl_ende;
$output["string"][] = trim($ar_string);
And now why did your intval() failed? Because if you right click and show source you will see in the array the value is:
<td>1050
So this can't convert to a int! And the <td> you don't see, because it's a html tag
Now you can easy extract only the number with this lines:
$tabelle["string"]["0"] = filter_var($tabelle["string"]["0"], FILTER_SANITIZE_NUMBER_INT);
echo $number = intval($tabelle["string"]["0"]);
Output:
1050

If I understand your code and logic correctly.
try replace:
$output[start][] = $ar_start;
$output[ende][] = $ar_ende - $ar_start + $anzahl_ende;
$output[string][] = trim($ar_string);
to this:
$
output['start'][] = intval($ar_start);
$output['ende'][] =intval( $ar_ende - $ar_start + $anzahl_ende);
$output['string'][] = intval(trim($ar_string));

Related

Get nearest sequence result from an array and given pattern with PHP

I am trying to get year and month from the letters using established sequence. I know that the sequence is based on the following letters:
$letters = array('B','C','D','F','G','H','J','K','L','M','N','P','R','S','T','V','W','X','Y','Z');
It started with 0000BBB and when it reaches 9999 it becomes BBC, BBD etc. So I don't need the numbers in that case and only letters as I have a list of last registered sequence per year and month like this:
$plates = array(
array('2018','KHF','KHX','KJV','KKN','KLM','KML','KNK','KPD','KPR','KPT','----','----'),
array('2017','JWN','JXF','JYB','JYT','JZP','KBM','KCH','KCV','KDK','KFB','KFV','KGN'),
array('2016','JLN','JMF','JMY','JNR','JPK','JRG','JRZ','JSL','JTB','JTR','JVH','JVZ'),
array('2015','JCK','JCY','JDR','JFG','JFW','JGP','JHJ','JHT','JJH','JJW','JKK','JKZ'),
array('2014','HVN','HVZ','HWM','HXB','HXN','HYD','HTY','HZB','HZL','HZZ','JBL','JBY'),
array('2013','HNT','HPC','HPN','HPY','HRK','HRX','HSK','HSR','HSZ','HTK','HTV','HVF'),
array('2012','HJC','HJM','HKB','HKL','HKX','HLK','HLW','HMD','HML','HMT','HNC','HNK'),
array('2011','HBP','HCB','HCR','HDC','HDR','HFF','HFT','HGC','HGM','HGX','HHH','HHT'),
array('2010','GTC','GTS','GVM','GWC','GWV','GXP','GYD','GYM','GYX','GZJ','GZT','HBG'),
array('2009','GKS','GLC','GLP','GMC','GMN','GNF','GNY','GPJ','GPW','GRM','GSC','GSR'),
array('2008','FZR','GBN','GCK','GDH','GFC','GFY','GGV','GHG','GHT','GJJ','GJV','GKH'),
array('2007','FKY','FLV','FNB','FNZ','FRC','FSJ','FTP','FVJ','FWC','FXB','FXY','FYY'),
array('2006','DVW','DWT','DXZ','DYY','FBC','FCJ','FDP','FFK','FGF','FHD','FJD','FKC'),
array('2005','DFZ','DGX','DHZ','DKB','DLD','DMJ','DNP','DPK','DRG','DSC','DTB','DVB'),
array('2004','CRV','CSS','CTT','CVR','CWR','CXT','CYY','CZP','DBJ','DCH','DDG','DFF'),
array('2003','CDV','CFM','CGJ','CHF','CJC','CKB','CLD','CLV','CMM','CNK','CPF','CRC'),
array('2002','BSL','BTF','BTZ','BVW','BWT','BXP','BYP','BZF','BZV','CBP','CCH','CDC'),
array('2001','BFJ','BGF','BHG','BJC','BKB','BLC','BMF','BMW','BNL','BPG','BRB','BRT'),
array('2000','---','---','---','---','---','---','---','---','BBJ','BCD','BCY','BDR')
);
That means that array index 0 is the year and from 1 to 12 would be month. I am trying to find a match but then realize I can not search exact value and need to look for nearest value based on letters.
I would deeply appreciate if anyone could direct me in right direction what would be the best method of doing this.
This is a test so far but this will just return an exact match, I would have to search any possible letters such as KHW as an example that would have to match as nearest value to KHX
foreach ($plates as $key => $val) {
$search = array_search('KHX', $plates[$key]);
if($search){
echo $search."\n";
echo $plates[$key][0];
break;
}
}
You can solve it with O(log n) with a binary search. But in a more straightforward solution, you can solve it with O(n).
You can calculate the difference between each word with the below algorithm.
‍‍
<?php
function strToInt($str)
{
$result = 0;
for ($i = 0; $i < strlen($str); $i++) {
$result = $result * 100 + ord($str[$i]);
}
return $result;
}
function find($searchStr)
{
$plates = [
['2018','KHF','KHX','KJV','KKN','KLM','KML','KNK','KPD','KPR','KPT','----','----'],
['2017','JWN','JXF','JYB','JYT','JZP','KBM','KCH','KCV','KDK','KFB','KFV','KGN'],
['2016','JLN','JMF','JMY','JNR','JPK','JRG','JRZ','JSL','JTB','JTR','JVH','JVZ'],
['2015','JCK','JCY','JDR','JFG','JFW','JGP','JHJ','JHT','JJH','JJW','JKK','JKZ'],
['2014','HVN','HVZ','HWM','HXB','HXN','HYD','HTY','HZB','HZL','HZZ','JBL','JBY'],
['2013','HNT','HPC','HPN','HPY','HRK','HRX','HSK','HSR','HSZ','HTK','HTV','HVF'],
['2012','HJC','HJM','HKB','HKL','HKX','HLK','HLW','HMD','HML','HMT','HNC','HNK'],
['2011','HBP','HCB','HCR','HDC','HDR','HFF','HFT','HGC','HGM','HGX','HHH','HHT'],
['2010','GTC','GTS','GVM','GWC','GWV','GXP','GYD','GYM','GYX','GZJ','GZT','HBG'],
['2009','GKS','GLC','GLP','GMC','GMN','GNF','GNY','GPJ','GPW','GRM','GSC','GSR'],
['2008','FZR','GBN','GCK','GDH','GFC','GFY','GGV','GHG','GHT','GJJ','GJV','GKH'],
['2007','FKY','FLV','FNB','FNZ','FRC','FSJ','FTP','FVJ','FWC','FXB','FXY','FYY'],
['2006','DVW','DWT','DXZ','DYY','FBC','FCJ','FDP','FFK','FGF','FHD','FJD','FKC'],
['2005','DFZ','DGX','DHZ','DKB','DLD','DMJ','DNP','DPK','DRG','DSC','DTB','DVB'],
['2004','CRV','CSS','CTT','CVR','CWR','CXT','CYY','CZP','DBJ','DCH','DDG','DFF'],
['2003','CDV','CFM','CGJ','CHF','CJC','CKB','CLD','CLV','CMM','CNK','CPF','CRC'],
['2002','BSL','BTF','BTZ','BVW','BWT','BXP','BYP','BZF','BZV','CBP','CCH','CDC'],
['2001','BFJ','BGF','BHG','BJC','BKB','BLC','BMF','BMW','BNL','BPG','BRB','BRT'],
['2000','---','---','---','---','---','---','---','---','BBJ','BCD','BCY','BDR']
];
$minYear = null;
$minKey = null;
$minDiff = strToInt('ZZZ');
$searchInt = strToInt($searchStr);
for ($i = 0; $i < count($plates); $i++) {
for ($j = 1; $j < 13; $j++) {
if(abs($searchInt - strToInt($plates[$i][$j])) < $minDiff) {
$minDiff = abs($searchInt - strToInt($plates[$i][$j]));
$minYear = $plates[$i][0];
$minKey = $plates[$i][$j];
}
}
}
return [$minYear, $minKey];
}
print_r(find('KHW'));
The code down below is by no means optimized, but it's rather a concept of how you might solve your problem.
//Flatten out array (one dimension without years and ----)
$flatten = array();
foreach($plates as $platevalues) {
foreach($platevalues as $pv) {
if ($pv != '---' && $pv != '----' && intval($pv) == 0) {
//Create a string only if valid letters included in the $letters-array
//This string is then added to the new array that is flattened out
$pv2 = '';
for($i=0;$i<strlen($pv);$i++) {
$letter = substr($pv,$i,1);
if (in_array($letter, $letters) !== false) {
$pv2 .= $letter;
}
}
$flatten[] = $pv2;
}
}
}
//Do the search
$search = 'GWN';
$search_result = '';
//Create a new search string based on first found in flattened
//plates array (first G, then GW, then GWN)
for($i=0;$i<strlen($search);$i++) {
foreach($flatten as $key=>$f) {
if (substr($search,0,$i+1) == substr($f,0,$i+1)) {
$search_result .= substr($search,$i,1);
break;
}
}
}
/*
$search_result is: GW
*/
//Create a new array where all items that begins with GW are included
$result = [];
foreach($flatten as $key=>$item) {
if (substr($search_result,0,strlen($search_result)) ==
substr($item,0,strlen($search_result))) {
$result[] = $item;
}
}
/*
$result =
array (size=2)
0 => string 'GWC' (length=3)
1 => string 'GWV' (length=3)
*/
//Create an array with total ASCII-value for each item
//in the $result array above
$result_o = [];
foreach($result as $item) {
$o = 0;
for($i=0;$i<strlen($item);$i++) {
$o += ord(substr($item,$i,1));
}
$result_o[]= $o;
}
/*
$result_o =
array (size=2)
0 => int 225
1 => int 244
*/
//Get the total ASCII-value for the original search string
$search_o = 0;
for($i=0;$i<strlen($search);$i++) {
$search_o += ord(substr($search,$i,1));
}
/*
$search_ o = 236
*/
//Find closest value in the $result_o (ASCII) - array compared (225,244)
//to the original $search_o ASCII value above (236)
$closest = 0;
$use_key = 0;
foreach($result_o as $key=>$item) {
if ($closest == 0 || abs($search_o - $closest) > abs($item - $search_o)) {
$closest = $item;
$use_key = $key;
}
}
/*
$closest = 244 (it's closer to 236 than 225 is)
$use_key = 1
*/
To get the result you have:
/*
$result =
array (size=2)
0 => string 'GWC' (length=3)
1 => string 'GWV' (length=3)
*/
//This should print out GWV
echo 'result=' . $result[$use_key];

Convert String to custom array PHP

i have problem in my function php .
My function php is to check coordinates whether the coordinates are in polygons .
the problem is , i call polygon latlong from database and type data is string and convert to custom array .
this my function
function containsMaps($point1,$value1)
{
$point = preg_split ("/\,/", $point1);
$value = $value1;
foreach(explode('),(',trim($value,'()')) as $single_array){
$sub_array= array();
foreach(explode(',',$single_array) as $sbs_array)
{
$sub_array = array($sbs_array);
}
$polygon = array($sub_array);
}
if($polygon[0] != $polygon[count($polygon)-1])
$polygon[count($polygon)] = $polygon[0];
$j = 0;
$oddNodes = false;
$x = $point[1];
$y = $point[0];
$n = count($polygon);
for ($i = 0; $i < $n; $i++)
{
$j++;
if ($j == $n)
{
$j = 0;
}
if ((($polygon[$i][0] < $y) && ($polygon[$j][0] >= $y)) || (($polygon[$j][0] < $y) && ($polygon[$i][0] >=
$y)))
{
if ($polygon[$i][1] + ($y - $polygon[$i][0]) / ($polygon[$j][0] - $polygon[$i][0]) * ($polygon[$j][1] -
$polygon[$i][1]) < $x)
{
$oddNodes = !$oddNodes;
}
}
}
return $oddNodes;
}
the polygon data from database like this :
(-6.268649975971238, 106.69106266990389),(-6.267711482694832, 106.72625325217928),(-6.288272630052733, 106.72736905112947),(-6.288699201273463, 106.69106266990389)
if i use static data like this , the function working :
$polygon = array(
array(-6.2811957386588855, 106.70141951079609),
array(-6.281142416506361, 106.70432702536823),
array(-6.2781776962328815, 106.70438066954853),
array(-6.2781776962328815, 106.70136586661579),
);
Your code to split the incoming data isn't quite right. This will work:
foreach(explode('),(',trim($value,'()')) as $single_array){
$polygon[] = explode(',',$single_array);
}
Output:
array (
0 =>
array (
0 => '-6.268649975971238',
1 => ' 106.69106266990389',
),
1 =>
array (
0 => '-6.267711482694832',
1 => ' 106.72625325217928',
),
2 =>
array (
0 => '-6.288272630052733',
1 => ' 106.72736905112947',
),
3 =>
array (
0 => '-6.288699201273463',
1 => ' 106.69106266990389',
),
)
Demo on 3v4l.org
Note this will give you string values, if you want floating point values, use code like this:
foreach(explode('),(',trim($value,'()')) as $single_array){
list ($x, $y) = explode(',',$single_array);
$polygon[] = array((double)$x, (double)$y);
}
Demo on 3v4l.org

Set color shade based on variable number with PHP

Ok, I don't even know where to start with this one! I'll try and explain what I want to achieve, and we'll go from there....
I have a list of dates each with an associated number, say from 20-100. What I want to do is to output the date in a shade which represents the associated number. So 20 would display in a light blue and 100 in a dark blue. My code so far looks like this...
dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
$maxNum = max($dateArray);
$minNum = min($dateArray);
foreach($dateArray AS $date => $num){
$lightest = 'rgb(204,204,255)';
$darkest = 'rgb(0, 0, 179)';
///magic that converts $num into $shade goes here///
echo "<span style='color:$shade'>$date</span><br>"
}
Any ideas? Thanks
I would do something like that :
$dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
// get max and min values
$maxNum = max($dateArray);
$minNum = min($dateArray);
// set rgb values for max and min
$lightest = array(204, 204, 255);
$darkest = array(0, 0, 179);
foreach($dateArray AS $date => $num)
{
// get a "delta" where the current num value is
$delta = ($num / $maxNum) - $minNum;
// get a pro-rata values thanks to $delta
$shadesNum = array(
$delta * ($lightest[0] - $darkest[0]) + $darkest[0],
$delta * ($lightest[1] - $darkest[1]) + $darkest[1],
$delta * ($lightest[2] - $darkest[2]) + $darkest[2]
);
echo "<span style='rgb(".implode(',', $shadesNum).")'>$date</span><br>";
}
Some languages have a "lerp" function - linear interpolation. Quite useful.
My suggestion:
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade($x1) . "<br />\n";
function getshade($num) {
$rlight = 204;
$glight = 204;
$blight = 255;
$rdark = 0;
$gdark = 0;
$bdark = 179;
$lightnum = 20;
$darknum = 100;
$k01 = ($num-$lightnum)/($darknum-$lightnum); // 0 to 1
$rshade = ilerp($rlight, $rdark, $k01);
$gshade = ilerp($glight, $gdark, $k01);
$bshade = ilerp($blight, $bdark, $k01);
return "rgb($rshade,$gshade,$bshade)"; }
function lerp($start, $end, $k01) { // linear interpolation
return $k01*$end + (1.0-$k01)*$start; }
function ilerp($start, $end, $k01) { // integer lerp
return intval($k01*$end + (1.0-$k01)*$start); }
EDIT: Same thing but better:
$rgblight = [204,204,255];
$rgbdark = [0,0,179];
$numlight = 20;
$numdark = 100;
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade2($x1, $numlight, $numdark, $rgblight, $rgbdark) . "<br />\n";
function getshade2($num, $numlight, $numdark, $rgblight, $rgbdark) {
$k01 = ($num-$numlight)/($numdark-$numlight);
for ($i1=0; $i1<3; $i1+=1)
$rgb[$i1] = ilerp($rgblight[$i1], $rgbdark[$i1], $k01);
return "rgb({$rgb[0]},{$rgb[1]},{$rgb[2]})"; }

Simple random generator script not working

I have this script but it's not working, not sure how to fix it, any tips please? all I get out the other end is the letter "t"
Thanks :)
<?php
$cachefile = './current_t_id';
$time = $id = null; // assume we have no cached quote
$change_every = 3600; // seconds
$pages = array(1 => 'text1-1.php', 2 => 'text1-2.php');
foreach($pages as $pagekey => $page){
if($pagekey == $siteId){
include($page);
}
}
// if cached quote exists, load it
if(is_file($cachefile)) {
list($time, $id) = explode(' ', file_get_contents($cachefile));
}
// if no cached quote or duration expired, change it
if(!$time || time() - $time > $change_every) {
srand ((double) microtime() * 100000);
$id = rand(0,count($page)-1);
file_put_contents($cachefile, time().' '.$id); // update cache
}
// echo the quote, be it cached or freshly picked
echo ($page[$id]);
?>
OK am going to give you 3 different examples
Variables
$quotes = array (
"hello",
"baba",
"luke"
);
$pages = array(1 => 'text1-1.php', 2 => 'text1-2.php');
A. Using Random Quotes
// Using Ramdom Quptes
$key = array_rand ( $quotes );
echo $quotes [$key];
//Or
include($pages[$key]) ;
B. Using Robin
// Using Robin
$cacheFile = "robin.cache";
$robin = null;
$quotesID = intval ( file_get_contents ( $cacheFile ) );
$totalQuotes = count ( $quotes );
$key = ($quotesID < ($totalQuotes - 1)) ? $quotesID ++ : 1;
file_put_contents ( $cacheFile, $quotesID );
echo $quotes [$key];
//Or
include($pages[$key]) ;
Using Timer
// Using Timer
$cacheFile = "timer.cache";
$expiration = 3600;
$robin = null;
list($quotesID, $time) = explode(' ', file_get_contents($cacheFile));
$totalQuotes = count ( $quotes );
if($time < (time() - $expiration))
{
$key = mt_rand(0,count($pages)-1);
file_put_contents($cacheFile, time().' '.$id);
}
echo $quotes [$key];
//Or
include($pages[$key]) ;
I hope your issue can be resolved now
Thanks
:)

PHP How can I get HEX Color code from array of R + G + B?

I have an array:
Array
(
[red] => 252
[green] => 168
[blue] => 166
[alpha] => 0
)
It's an output of function imagecolorsforindex.
How can I get a HTML code from these elements? For example: #99CCFF
Strictly speaking you can't, since alpha is not supported. But since the alpha is 0, we can assume that it won't matter. As such, pass each value into sprintf() with a format specifier of %02x for each element.
c = sprintf('#%02x%02x%02x', val['red'], val['green'], val['blue']);
PHP Convert RGB from/to HTML hex color
rgb2html($array[0], $array[1], $array[2])
There's a function contributed in the comments of this page of the PHP manual.
<?PHP
function rgb2hex2rgb($c){
if(!$c) return false;
$c = trim($c);
$out = false;
if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
$c = str_replace('#','', $c);
$l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);
if($l){
unset($out);
$out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
$out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
$out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
}else $out = false;
}elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
$spr = str_replace(array(',',' ','.'), ':', $c);
$e = explode(":", $spr);
if(count($e) != 3) return false;
$out = '#';
for($i = 0; $i<3; $i++)
$e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));
for($i = 0; $i<3; $i++)
$out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];
$out = strtoupper($out);
}else $out = false;
return $out;
}
?>
Output
#FFFFFF =>
Array{
red=>255,
green=>255,
blue=>255,
r=>255,
g=>255,
b=>255,
0=>255,
1=>255,
2=>255
}
#FFCCEE =>
Array{
red=>255,
green=>204,
blue=>238,
r=>255,
g=>204,
b=>238,
0=>255,
1=>204,
2=>238
}
CC22FF =>
Array{
red=>204,
green=>34,
blue=>255,
r=>204,
g=>34,
b=>255,
0=>204,
1=>34,
2=>255
}
0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA
You can try this simple piece of code below.
$rgb = (123,222,132);
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);
This will return #7bde84

Categories