0

In my db there is a table that have some values like this[string]

100/100
50/100
40/80
7/70

I need to change this values in

100%
50%
50%
10%

How can i do this using only PHP/mysql code?

EDIT:this is the code:

foreach ($html->find('div.stat') as $status_raw){
    $status = $tag_pic_raw->src;
    $status = mysql_real_escape_string($status);
    $data->query("INSERT IGNORE INTO `tb` (`value`) VALUES ('".$status."')");
}

I have used a DOM inspector to get info from another site

8

4 Answers 4

4

Used explode() combined with some math.

$str = '40/80';
$vals = explode('/', $str);
$percent = (($vals[0] / $vals[1]) * 100).'%';
echo $percent;
Sign up to request clarification or add additional context in comments.

Comments

2

use explode() to divide up the values and then math them.

foreach($array as $val) // assuming all the (##/##) values are in an array
{
    $mathProblem = explode("/", $val);
    echo (intval($mathProblem[0]) / intval($mathProblem[1]) * 100)."%<br />";
}

2 Comments

another possibility is using list($num, $den) = explode("/", $val); which gives you two nice variables you can work with instead of indices
hadn't thought of that. clever way to make the code more aesthetically-pleasing/human-readable.
0

You can set up a function similar to this:

function math($one)
    {
        $new = explode("/", $one);
        $math = $new[0] / $new[1];
        $answer = $math * 100;
        return $answer."%";
    }

Then every time you need to query something, you can do it simply by doing this:

foreach ($results as $r)
{
    echo math($r);
}

This just makes it (I think) tidier and easier to read.

Comments

0

Use explode() :Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter( / in this case).

$arr=array('80/100','50/100','40/80');
foreach($arr as $str){
 $values = explode('/',$str);
 echo ((int)$values[0]/(int)$values[1])*100.'%<br/>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.