Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the closest value in PHP

Tags:

php

mysql

How to determine the RESULTS field in table users, base on USER SCORE field with the provisions of the value closest to SCORE BRAND field.

enter image description here

This is table Brand

    <table>
<tr>
<th>BRAND NAME</th>
<th>SCORE BRAND</th>
</tr>";
$sql = mysql_query("SELECT * FROM brand");
while($m=mysql_fetch_array($sql)){ 
echo "<tr> 
<td>$m[brand_name]</td>
<td>$m[score]</td><tr>";
}
</table>

This is table users

    <table>
<tr>
<th>USER NAME</th>
<th>SCORE USER</th>
<th>RESULT</th>
</tr>";
$sql2 = mysql_query("SELECT * FROM users");
while($u=mysql_fetch_array($sql2)){ 
echo "<tr> 
<td>$u[username]</td>
<td>$u[score]</td>
<td> ??? </td>
<tr>";
}
</table>
like image 950
Sigit Prasetya Avatar asked Jun 19 '17 07:06

Sigit Prasetya


People also ask

How do I find the nearest number in PHP?

Tip: To round a number UP to the nearest integer, look at the ceil() function.

How do you find the closest value in an array?

Find the closest value in array using reduce() The easiest way to do this is to use Math. abs(), so lets use that. With this function we check whether the absolute value of (b – 8) is less than the absolute value of (a – 8) and then return the winner.

How do I find the closest number in Javascript?

Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .


1 Answers

You can use subquery in selection to find proper brand for every selected user like this:

SELECT u.*, (
    SELECT b.id
    FROM brand AS b
    ORDER BY ABS(b.score - u.score) ASC, b.score DESC -- selects brands ordered by their difference from user's score
    LIMIT 1 -- get just the first brand (with score closest to user's)
)
FROM user AS u
like image 130
Roman Hocke Avatar answered Oct 15 '22 09:10

Roman Hocke