How to get rid of error: Undefined offset: 1 on line 20? I know it occurs becaouse Im calling array that's offset simply does not exist.
Silecing it wiht # just doesnt seem right at all.
//create an array with all x, y
for ($x = 1; $x <= 5; $x++) $array_x[] = $x;
for ($y = 1; $y <= 5; $y++) $array_y[] = $y;
$IN_x = "'" . implode("', '", $array_x) . "'";
$IN_y = "'" . implode("', '", $array_y) . "'";
$pullMapInfo = "SELECT x, y, value FROM mapinfo WHERE id='{$id}' AND x IN ({$IN_x}) AND y IN ({$IN_y})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
//create an associative array x, y => value
while ($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) {
$result[ $pullMapInfo3['x'] ][ $pullMapInfo3['y'] ] = $pullMapInfo3['value'];
}
//loop to display output
foreach ($array_x as $x) {
foreach ($array_y as $y) {
if (array_key_exists($x, $result) && array_key_exists($y, $result)) {
echo '<div class="castle_array" id="'.$x,'x',$y.'">'. $result[$x][$y] .'</div>
';
} else {
echo '<div class="castle_array" id="'.$x,'x',$y.'"></div>
';
}
}
}
2 for loops seems awkard
Replace this line:
if (array_key_exists($x, $result) && array_key_exists($y, $result)) {
with:
if (isset($result[$x][$y])) {
Documentation: isset
For Joseph Silber: Try this PHP fiddle
Your second call to array_key_exists should pass in $result[$x]:
if ( array_key_exists($x, $result) && array_key_exists($y, $result[$x]) ) {
// Code goes here...
}
Related
Basically i want to get the amount and the remaining value number but i didn't get the exact value.
this is my following code
$arr = [5000,2000];
$return = 0;
foreach($arr as $val) {
$sum = (3000 * 10) / 9;
if($val < $sum) {
$v += $val;
$return = ($v % $sum);
if($return == $v)
$return = 0;
} else {
$return = $val;
}
$amount = abs($val - $ret);
print_r("Return : ".$return . " Amount : " .$amount."<br>");
}
the result
Return : 5000 Amount : 5000
Return : 0 Amount : 2000
but that is wrong value, i want to get like this
Return : 1667 Amount : 3333
Return : 2000 Amount : 0
Summary :
I want to limit number base on $sum value and return the remaining value and get the amount,
so i write that code above but i can't figure it out.
sorry for my bad english
Thanks, sorry i'm new in php
If i understood you right. You need this.
$values = [5000, 2000];
foreach ($values as $value) {
$n = 3333;
$remain = $value - $n;
if ($remain < 0) {
print 'Return : ' . $value . ' Amount : 0';
} else {
print 'Return : ' . $remain . ' Amount : ' . $n;
}
}
I used this same code before and not like that just for one image at one time it is working fine there for showing img(stars)but now stars in first value is fine next it is collecting result with previous one
while ($query = mysql_fetch_array($tableone))
{
$Rating = $query['rating'];
$totalV = $query['total_votes'];
$commentcount = $query['comment_counts'];
if (!$Rating == 0 )
{
$number = $Rating / $totalV ;
$numbers = (round($number,3));
for ($x = 1 ; $x <= $numbers ; $x++)
{
$star .= '<img src="img/stars.gif" width="14%"/>';
}
$left = 5 - $numbers ;
for ($x = 1 ; $x <= $left ; $x++)
{
$result .='<img src="img/whitestar.gif" width="12%"/>';
}
if ( strpos($left, '.' ) == true)
{
$hs .= '<img src="img/halfwhitestar.gif" width="12%"/>';
}
$result1 = $star. $hs .$result;
}
else
{
$result1 ='Null';
}
if (empty($totalV))
{
$totalV = 'No votes';
}
$totalV ="/".$totalV;
$ratingbox = "<span id=\"ratingimg\">".$result1." </span>
<br/>
<span class=\"valueimg\">".$number.$totalV."</span>";
}
my Values in database of each image is
and this code is visible like this
this code i am using now for table for all images present in database including their some information...need guidance:S
Since you are concatenating strings during your loop, those strings just keep growing with each iteration of the loop.
I suggest that you reset these variables to blank strings upon each iteration of your while loop: $star, $hs, $result.
Something like this:
while ($query = mysql_fetch_array($tableone)) {
$star=$hs=$result='';
...
I'm asking MySQL for data, but it slows down the whole script. Yet I have no idea how to get this out of a loop. I tried converting it to PHP array but honestly after day of tries I failed.
<?php
$id = '1';
include_once 'include_once/connect.php';
for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
$xy = $x."x".$y;
$pullMapInfo = "SELECT value FROM mapinfo WHERE id='".$id."' AND xy='".$xy."'";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
if ($pullMapInfo3 = mysql_fetch_array($pullMapInfo2)) {
#some code
} else {
#some code
}
}
}
?>
How to get MySQL query $pullMapInfo2 out of loop to shorten loading it by asking once?
If you want to fire script on your localhost you can c&p whole thing :-)
I'm not sure what you have in your table, but considering you are basically looping through virtually everything in it, I'd say do a single query for the given Id and then sort out what you need from the larger dataset.
Especially if you are always pulling back essentially the complete dataset for each id, there's no reason to even bother with the IN query, just pull it all back into a single PHP array, and then iterate through that as needed.
Use a MySQL IN clause
<?php
$id = '1';
include_once 'include_once/connect.php';
// first we create an array with all xy
$array = array();
for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
$xy = $x."x".$y;
$array[] = $xy;
}
}
$in = "'" . implode("', '", $array) . "'";
$pullMapInfo = "SELECT xy, value FROM mapinfo WHERE id='".$id."' AND xy IN ({$in})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
// we create an associative array xy => value
$result = array();
while (($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) !== false) {
$result[ $pullMapInfo3['xy'] ] = $pullMapInfo3['value'];
}
// we make a loop to display expected output
foreach ($array as $xy)
{
if (array_key_exists($xy, $result)) {
echo '<div class="castle_array" style="background-image: url(tiles/'.$result[$xy].'.BMP)" id="'.$xy.'">'. $result[$xy] .'</div>';
} else {
echo '<div class="castle_array" id="'.$xy.'"></div>';
}
echo '<div class="clear_both"></div>';
}
?>
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/.
I Keep getting the following error and I was wondering on how to fix it.
Fatal error: Unsupported operand types on line 97
Its around this area of code listed below. I can list the full code if needed.
PHP code
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {
echo '(no votes cast)';
}
Here is Line 97
$avg = (round($total_rating_points / $total_ratings,1));
Here is the full code.
function getRatingText(){
$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$page = '3';
$sql1 = "SELECT COUNT(*)
FROM articles_grades
WHERE users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql1);
if (!mysqli_query($dbc, $sql1)) {
print mysqli_error($dbc);
return;
}
$total_ratings = mysqli_fetch_array($result);
$sql2 = "SELECT COUNT(*)
FROM grades
JOIN articles_grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql2);
if (!mysqli_query($dbc, $sql2)) {
print mysqli_error($dbc);
return;
}
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {
echo '(no votes cast)';
}
}
$total_rating_points is an array. you cannot divide it by a number.
(edited since the MySQL query was added to the question)
You've used mysql_fetch_array to get your result from MySQL, as the name suggests this returns an array. You can't do math like that on arrays.
You want to change your MySQL query to this:
$sql1 = "SELECT COUNT(*) as count
FROM articles_grades
WHERE users_articles_id = '$page'";
Change your mysql_fetch_array code to this:
$total_rating_points = mysql_result($result, 0, "count");
That will return the actual number, which you can then use for math. Change both of your queries to this format and you should be good to go.
That's usually caused when the type of one of your variables is something you're not expecting it to be.
$x = "8";
$y = 4;
$x / $y; // this is OK, PHP converts "8" to 8
$x = new FooObject();
$y = 4;
$x / $y; // PHP says "wtfmate??"
Dump out the variables $total_rating_points and $total_ratings:
var_dump($total_rating_points);
var_dump($total_ratings);
.. then work backwards through your code (checking debug_backtrace() if required) to find where it went awry.
Edit: duhhh.. I just looked at your code again and saw the issue. The $total_rating_points is an array, and this is the cause of the problem. How do you divide an array by a number? Answer: you can't.
Do you want to divide each of the members of the array by $total_ratings? eg:
// input: [2, 4, 6, 16] / 2
// output: [1, 2, 3, 8]
function divideArrayMembers($arr, $denominator) {
$ret = array();
foreach ($arr as $key => $val) {
$ret[$key] = $val / $denominator;
}
return $ret;
}
...or do you want to divide the total?
input: [2, 4, 6, 16] / 2
output: 14 // (2 + 4 + 6 + 16) / 2
function divideTotal($arr, $denominator) {
return array_sum($arr) / $denominator.
}
Use array_sum() on $total_rating_points and $total_ratings.
if($_REQUEST['cityCode'] != ''){
$_SESSION['Cri_locations'] = $_REQUEST["s"];
$_SESSION['Cri_DateFrom'] = $_REQUEST["startDate"];
$_SESSION['Cri_DateTo'] = $_REQUEST["endDate"];
$what_to_search_id =str_replace("AREA-","",$_REQUEST["cityCode"]);
$total_adults =0;
$total_childs =0;
$child_ages =0;
$no_of_room =0;
for($i=1;$i<=$_REQUEST["Cri_noofRooms"];$i++){
$check_adults =$_REQUEST['adults-r'.$i.''];
if($check_adults>0){
$adults =$_REQUEST['adults-r'.$i.''];
$childs =$_REQUEST['childs-r'.$i.''];
$childAge =$_REQUEST['childAge-r'.$i.''];
$packs_arr[] =array('adults'=>$adults,'childs'=>$childs,'childAge'=>$childAge);
$total_adults =$total_adults+$adults;
$total_childs =$total_childs+$childs;
$child_ages =$child_ages+$childAge;//error accours here pls help
$no_of_room =$no_of_room+1;
}
}