I have this script for my site and I think I have a problem in the for line. If I update my user_xp_amount with 256 the script works fine. However, when I update with a higher XP, such as 785, the script is showing me that I have level 1 instead of level 2 with 256xp. Why is this not behaving the way I desire?
PHP Script:
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$user_id = 4;
function get_user_xp($user_id, $mysqli) {
$sql = $mysqli->query("SELECT user_xp_amount FROM users_xp WHERE user_id='$user_id'");
$row = $sql->fetch_assoc();
return $row['user_xp_amount'];
}
$xp = array(0,256,785,1656,2654);
$my_xp = get_user_xp($user_id, $mysqli); // where 4 is my user id
for($i = 0; $i < count($xp); $i++) {
if($my_xp == $xp[$i]) {
echo 'I\'m on level ', ($i+1);
break;
}
else {
if(isset($xp[$i+1])) {
if($my_xp > $xp[$i] && $my_xp <= $xp[$i + 1]) {
echo 'My next level is ', ($i+2), ' and I need ', $xp[$i+1], ' more points for achieving it!';
break;
} else {
echo 'My next level is ', ($i+1), ' and I need ', $xp[$i], ' more points for achieving it!';
break;
}
}
}
}
?>
MySQL DB:
user_xp_id Primar bigint(20) | user_id bigint(20) | user_xp_amount bigint(20)
The reason it's not working can be found with some basic debugging: think through your for loop step by step. If that fails, try something like
// snip
for($i = 0; $i < count($xp); $i++) {
print $i; // show me which step I'm on
if($my_xp == $xp[$i]) {
// snip
Try that, and the reason will pop out at you.
This is an essential part of debugging: be careful what you assume. Your assumption is usually your mistake.
Only after you go through that exercise should you look any further into this answer. (You may not even want to!)
A hint that'll make it easier to code: you can keep reassigning values until you exit the loop.
$xp = array(0,256,785,1656,2654);
$my_xp = 254;
for($i = 0; $i < count($xp); $i++) {
// if we've looped beyond our xp, exit with last assigned (current) values
if($my_xp < $xp[$i]) { break; }
$my_level = $i;
// if index + 1 is in range, assign values
if($i+1<count($xp)) {
$next_level = $i+1;
$xp_needed = $xp[$i+1] - $my_xp;
// if index + 1 is out of range, give default values
} else {
$next_level = $i;
$xp_needed = 0;
}
}
printf("<div>Current Level: %d (%d xp)</div>" .
"<div>Next Level: %d (%d xp)</div>" .
"<div>XP Needed: %d</div>",
$my_level +1, // correct off-by-1 error of index
$my_xp,
$next_level +1, // correct off-by-1 error of index
$xp[$next_level],
$xp_needed
);
Related
This code is working fine when the array length is 8 or 10 only. When we are checking this same code for more than 10 array length.it get loading not showing the results.
How do reduce my code. If you have algorithm please share. Please help me.
This program working flow:
$allowed_per_room_accommodation =[2,3,6,5,3,5,2,5,4];
$allowed_per_room_price =[10,30,60,40,30,50,20,60,80];
$search_accommodation = 10;
i am get subsets = [5,5],[5,3,2],[6,4],[6,2,2],[5,2,3],[3,2,5]
Show lowest price room and then equal of 10 accommodation; output like as [5,3,2];
<?php
$dp=array(array());
$GLOBALS['final']=[];
$GLOBALS['room_key']=[];
function display($v,$room_key)
{
$GLOBALS['final'][] = $v;
$GLOBALS['room_key'][] = $room_key;
}
function printSubsetsRec($arr, $i, $sum, $p,$dp,$room_key='')
{
// If we reached end and sum is non-zero. We print
// p[] only if arr[0] is equal to sun OR dp[0][sum]
// is true.
if ($i == 0 && $sum != 0 && $dp[0][$sum]) {
array_push($p,$arr[$i]);
array_push($room_key,$i);
display($p,$room_key);
return $p;
}
// If $sum becomes 0
if ($i == 0 && $sum == 0) {
display($p,$room_key);
return $p;
}
// If given sum can be achieved after ignoring
// current element.
if (isset($dp[$i-1][$sum])) {
// Create a new vector to store path
// if(!is_array(#$b))
// $b = array();
$b = $p;
printSubsetsRec($arr, $i-1, $sum, $b,$dp,$room_key);
}
// If given $sum can be achieved after considering
// current element.
if ($sum >= $arr[$i] && isset($dp[$i-1][$sum-$arr[$i]]))
{
if(!is_array($p))
$p = array();
if(!is_array($room_key))
$room_key = array();
array_push($p,$arr[$i]);
array_push($room_key,$i);
printSubsetsRec($arr, $i-1, $sum-$arr[$i], $p,$dp,$room_key);
}
}
// Prints all subsets of arr[0..n-1] with sum 0.
function printAllSubsets($arr, $n, $sum,$get=[])
{
if ($n == 0 || $sum < 0)
return;
// Sum 0 can always be achieved with 0 elements
// $dp = new bool*[$n];
$dp = array();
for ($i=0; $i<$n; ++$i)
{
// $dp[$i][$sum + 1]=true;
$dp[$i][0] = true;
}
// Sum arr[0] can be achieved with single element
if ($arr[0] <= $sum)
$dp[0][$arr[0]] = true;
// Fill rest of the entries in dp[][]
for ($i = 1; $i < $n; ++$i) {
for ($j = 0; $j < $sum + 1; ++$j) {
// echo $i.'d'.$j.'.ds';
$dp[$i][$j] = ($arr[$i] <= $j) ? (isset($dp[$i-1][$j])?$dp[$i-1][$j]:false) | (isset($dp[$i-1][$j-$arr[$i]])?($dp[$i-1][$j-$arr[$i]]):false) : (isset($dp[$i - 1][$j])?($dp[$i - 1][$j]):false);
}
}
if (isset($dp[$n-1][$sum]) == false) {
return "There are no subsets with";
}
$p;
printSubsetsRec($arr, $n-1, $sum, $p='',$dp);
}
$blockSize = array('2','3','6','5','3','5','2','5','4');
$blockvalue = array('10','30','60','40','30','50','20','60','80');
$blockname = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese");
$processSize = 10;
$m = count($blockSize);
$n = count($processSize);
// sum of sets in array
printAllSubsets($blockSize, $m, $processSize);
$final_subset_room = '';
$final_set_room_keys = '';
$final_set_room =[];
if($GLOBALS['room_key']){
foreach ($GLOBALS['room_key'] as $set_rooms_key => $set_rooms) {
$tot = 0;
foreach ($set_rooms as $set_rooms) {
$tot += $blockvalue[$set_rooms];
}
$final_set_room[$set_rooms_key] = $tot;
}
asort($final_set_room);
$final_set_room_first_key = key($final_set_room);
$final_all_room['set_room_keys'] = $GLOBALS['room_key'][$final_set_room_first_key];
$final_all_room_price['set_room_price'] = $final_set_room[$final_set_room_first_key];
}
if(isset($final_all_room_price)){
asort($final_all_room_price);
$final_all_room_first_key = key($final_all_room_price);
foreach ($final_all_room['set_room_keys'] as $key_room) {
echo $blockname[$key_room].'---'. $blockvalue[$key_room];
echo '<br>';
}
}
else
echo 'No Results';
?>
I'm assuming your task is, given a list rooms, each with the amount of people it can accommodate and the price, to accommodate 10 people (or any other quantity).
This problem is similar to 0-1 knapsack problem which is solvable in polynomial time. In knapsack problem one aims to maximize the price, here we aim to minimize it. Another thing that is different from classic knapsack problem is that full room cost is charged even if the room is not completely occupied. It may reduce the effectiveness of the algorithm proposed at Wikipedia. Anyway, the implementation isn't going to be straightforward if you have never worked with dynamic programming before.
If you want to know more, CLRS book on algorithms discusses dynamic programming in Chapter 15, and knapsack problem in Chapter 16. In the latter chapter they also prove that 0-1 knapsack problem doesn't have trivial greedy solution.
Up until now I've always been limiting my pages for any pagination simply using MySQL LIMIT. It's been performing well.
However... Now I've written an application that grabs the data from 3 separate MySQL tables, after that I'm using array_multisort() to sort them.
The main issue here is that it is used for SMS messages(gammu smsd). If I write a message consisting of let's say 900 characters - it is split to 7 entries in the database. It is split every 139 characters (the number might be different sometimes)
Below code somewhat fixes this issue based on 'SequencePosition' field in the database.
So if I were to LIMIT it using MySQL I would have less results than I specified since MySQL has no idea what I'm doing with the data later.
I hope it makes sense to you guys.
How would you solve this issue? Can you think of a better way to do it? I mean- grabbing all the data from the table is rarely a good idea ;(
See PHP code below.
<?php
if(isset($_SESSION['id']))
{
if(isset($_GET['contact_number']) && ($_GET['contact_name']))
{
if (isset($_GET["page"]))
{
$page = $_GET["page"];
}
else
{
$page = 1 ;
}
$gmessages_page = 30; //this is actually a static value, normally it resides in a config file
$start_from = ($page-1) * $gmessages_page;
$contact_number = base64_decode($_GET['contact_number']);
$contact_name = base64_decode($_GET['contact_name']);
$query_inbox = "SELECT ReceivingDateTime, SenderNumber, TextDecoded FROM inbox WHERE SenderNumber='$contact_number' ORDER BY ReceivingDateTime";
$query_sentitems = "SELECT SendingDateTime, DestinationNumber, TextDecoded, Status, SequencePosition FROM sentitems WHERE DestinationNumber='$contact_number' ORDER BY SendingDateTime";
$query_outbox = "SELECT SendingDateTime, DestinationNumber, TextDecoded FROM outbox WHERE DestinationNumber='$contact_number' ORDER BY SendingDateTime";
$result_inbox = $conn->query($query_inbox);
$result_sentitems = $conn->query($query_sentitems);
$result_outbox = $conn->query($query_outbox);
if(!$result_inbox || !$result_sentitems || !$result_outbox)
{
die("Błąd połączenia z bazą (!RESULT)");
}
$rows_inbox = $result_inbox->num_rows;
$rows_sentitems = $result_sentitems->num_rows;
$rows_outbox = $result_outbox->num_rows;
if($rows_inbox == 0 || $rows_sentitems == 0)
{
$conn->close();
}
//inbox
$inbox_person = $contact_name;
for($j = 0; $j < $rows_inbox ; ++$j)
{
$result_inbox->data_seek($j);
$row_inbox = $result_inbox->fetch_array(MYSQLI_NUM);
$inbox_date[] = $row_inbox[0];
$inbox_number = $row_inbox[1];
$inbox_text[] = $row_inbox[2];
$sent_status[] = 0;
$sent_sequence_position[] = 0;
$inbox_type[] = 1;
}
for($j = 0; $j < $rows_sentitems ; ++$j)
{
$result_sentitems->data_seek($j);
$row_sentitems = $result_sentitems->fetch_array(MYSQLI_NUM);
if($row_sentitems[4] == 1)
{
$sent_sequence_position[] = $row_sentitems[4];
$inbox_date[] = $row_sentitems[0];
$inbox_text[] = $row_sentitems[2];
$sent_status[] = $row_sentitems[3];
$inbox_type[] = 2;
}
else
{
$inbox_text[sizeof($inbox_type) - 1] .= $row_sentitems[2];
}
}
for($j = 0; $j < $rows_outbox ; ++$j)
{
$result_outbox->data_seek($j);
$row_outbox = $result_outbox->fetch_array(MYSQLI_NUM);
$inbox_date[] = $row_outbox[0];
$inbox_text[] = $row_outbox[2];
$sent_status[] = "QueuedForSending";
$inbox_type[] = 2;
}
$number_of_records = sizeof($inbox_date);
$number_of_pages = ceil($number_of_records / $gmessages_page);
array_multisort($inbox_date, $inbox_text, $inbox_type, $sent_status, $sent_sequence_position);
$smarty->assign("inbox_date", $inbox_date);
$smarty->assign("inbox_text", $inbox_text);
$smarty->assign("inbox_number", $inbox_number);
$smarty->assign("inbox_person", $contact_name);
$smarty->assign("inbox_type", $inbox_type);
$smarty->assign("sent_status", $sent_status);
$smarty->assign("start_from", $start_from);
$smarty->assign("gmessages_page", $gmessages_page);
$smarty->assign("number_of_pages", $number_of_pages);
$smarty->assign("number_of_records", $number_of_records);
$smarty->assign("sent_sequence_position", $sent_sequence_position);
$smarty->assign("page", $page);
//for $_GET after sending SMS
$smarty->assign("contact_number_enc", $_GET['contact_number']);
$smarty->assign("contact_name_enc", $_GET['contact_name']);
$smarty->display('templates/conversation_body.tpl');
}
}
else
{
$smarty->display('templates/login_body.tpl');
}
I have been working on my scoring system and came accros this.
I have 4 vars.
$newscore
$score1
$score2
$score3
I want to see if new score is lower than the 3 others, and if so which ones. The scoring system requires you to have the lowest possible score.
I have the following code:
if($newscore > $score1){
if($newscore > $score2){
if($newscore < $score3){
//has to be score3 to replace.
}
}else{
...
}
}
But what I'm wondering is if I will have to continue on with all these if statements, or is there something a lot shorter and easier? I need to replace the the score that it is smaller than, but not the one its larger than. Score 1 2 and 3 are all the players stats. And if I do have to continue on with all the if statements, how would the code look (its baffling my logic)?
you should probably use an array
$scores = array(8, 15, 10); //previous scores
$new_score = 5;
$new_score_smallest = true;
foreach($scores as $score) {
if($score < $new_score) {
$new_score_smallest = false;
}
}
if($new_score_smallest) {
echo "Best score!";
}
else {
echo "Not the best score :(";
}
If you only want to remember the 3 best scores:
$scores = array(5, 6, 8);
$new_score = 7;
for($i = 0; $i < count($scores); $i++) {
if($new_score < $scores[$i]) {
$scores[$i] = $new_score;
break;
}
}
You could do something like the following:
EDIT: As you're using a database, you would execute the query similar to this:
SELECT scores FROM scores_table replacing the table name and column name with your corresponding data.
$scores = [$score1, $score2] // add as many as you like
$new_score = $scores[0]; // assign a baseline
foreach ($scores as $score) {
if ($score < $new_score) {
$new_score = $score;
}
}
Hope that helps.
You can use array_search and min
$newscore = 2;
$scores = array($score1, $score2, $score3);
if($newscore < min($scores)){
$scores[array_search(min($scores), $scores)] = $newscore;
}
array $score lowest score will be updated if $newscore is inferior
Put your scores in an array or anything iterable (like a query result, whether you use PDO or mysqli).
Let's say your scores are in $scores array (it will be the same if $score is a PDOStatement for example) and ordered (use ORDER ASC in your query):
$scores = [105, 201, 305];
$newscore = '186';
$hiscore = false;
$beaten = [];
foreach ($score as $k => $score) {
if ($newscore > $score) {
$hiscore = true;
$beaten[] = $score;
unset($scores[$k]);
}
}
if ($hiscore) {
echo 'New high score!'.PHP_EOL;
echo 'Better than '.implode(', ', $beaten).PHP_EOL;
echo 'But not better than '.implode(', ', $scores);
} else {
echo 'Try harder!';
}
<?php
$newscore = 78;
$score1 = 23;
$score2 = 201;
$score3 = 107;
$max = max([$score1, $score2, $score3]);
if ($max < $newscore) {
echo "New best score ! ({$newscore})";
} else {
echo "Not the best score !\nCurrent: {$newscore}\nBest: {$max}";
}
I have an interface where a user will enter the name of a company. It then compares what they typed to current entries in the database, and if something similar is found it presents them with options (in case they misspelled) or they can click a button which confirms what they typed is definitely new and unique.
The problem I am having is that it is not very accurate and often brings up dozens of "similar" matches that aren't that similar at all!
Here is what I have now, the first large function I didn't make and I am not clear on what exactly it does. Is there are much simpler way to acheive what I want?
// Compares strings and determines how similar they are based on a nth letter split comparison.
function cmp_by_optionNumber($b, $a) {
if ($a["score"] == $b["score"]) return 0;
if ($a["score"] > $b["score"]) return 1;
return -1;
}
function string_compare($str_a, $str_b)
{
$length = strlen($str_a);
$length_b = strlen($str_b);
$i = 0;
$segmentcount = 0;
$segmentsinfo = array();
$segment = '';
while ($i < $length)
{
$char = substr($str_a, $i, 1);
if (strpos($str_b, $char) !== FALSE)
{
$segment = $segment.$char;
if (strpos($str_b, $segment) !== FALSE)
{
$segmentpos_a = $i - strlen($segment) + 1;
$segmentpos_b = strpos($str_b, $segment);
$positiondiff = abs($segmentpos_a - $segmentpos_b);
$posfactor = ($length - $positiondiff) / $length_b; // <-- ?
$lengthfactor = strlen($segment)/$length;
$segmentsinfo[$segmentcount] = array( 'segment' => $segment, 'score' => ($posfactor * $lengthfactor));
}
else
{
$segment = '';
$i--;
$segmentcount++;
}
}
else
{
$segment = '';
$segmentcount++;
}
$i++;
}
// PHP 5.3 lambda in array_map
$totalscore = array_sum(array_map(function($v) { return $v['score']; }, $segmentsinfo));
return $totalscore;
}
$q = $_POST['stringA'] ;
$qLengthMin = strlen($q) - 5 ; // Part of search calibration. Smaller number = stricter.
$qLengthMax = strlen($q) + 2 ; // not in use.
$main = array() ;
include("pdoconnect.php") ;
$result = $dbh->query("SELECT id, name FROM entity_details WHERE
name LIKE '{$q[0]}%'
AND CHAR_LENGTH(name) >= '$qLengthMin'
#LIMIT 50") ; // The first letter MUST be correct. This assumption makes checker faster and reduces irrelivant results.
$x = 0 ;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$percent = string_compare(strtolower($q), strtolower(rawurldecode($row['name']))) ;
if($percent == 1) {
//echo 1 ;// 1 signifies an exact match on a company already in our DB.
echo $row['id'] ;
exit() ;
}
elseif($percent >= 0.6) { // Part of search calibration. Higher deci number = stricter.
$x++ ;
$main[$x]['name'] = rawurldecode($row['name']) ;
$main[$x]['score'] = round($percent, 2) * 100;
//array_push($overs, urldecode($row['name']) . " ($percent)<br />") ;
}
}
usort($main, "cmp_by_optionNumber") ;
$z = 0 ;
echo '<div style="overflow-y:scroll;height:175px;width:460px;">' ;
foreach($main as $c) {
if($c['score'] > 100) $c['score'] = 100 ;
if(count($main) > 1) {
echo '<div id="anysuggested' . $z . '" class="hoverdiv" onclick="selectAuto(' . "'score$z'" . ');">' ;
}
else echo '<div id="anysuggested' . $z . '" class="hoverdiv" style="color:#009444;" onclick="selectAuto(' . "'score$z'" . ');">' ;
echo '<span id="autoscore' . $z . '">' . $c['name'] . '</span></div>' ;
$z++ ;
}
echo '</div>' ;
Comparing strings is a huge topic and there are many ways to do it. One very common algorithm is called the Levenshtein difference. This is a native implementation in PHP but none in MySQL. There is however an implementation here that you could use.
You need aproximate/fuzzy string matching.
Read more about
http://php.net/manual/en/function.levenshtein.php, http://www.slideshare.net/kyleburton/fuzzy-string-matching
The best way would be to use some index based search engine like SOLR http://lucene.apache.org/solr/.
When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.