Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Raphael C.

[Resolvido] Transformar string em operação matemática

Recommended Posts

Bom dia à todos. Eu estou com um pequeno problema: preciso transformar uma string que recebo da DB em uma operação matemática.

O código é o seguinte:

$slotquery = row(query("SELECT `attribute` FROM {{table}} WHERE id='{$userrow["slot1id"]}' LIMIT 1", "drops"));
$newvalue = $userrow["attack"] . $slotquery[1]["attribute"];

query("UPDATE {{table}} SET `attack`='{$newvalue}' WHERE `uid`='{$userrow["id"]}';", "drops");

 

No caso, o valor de "$newvalue" seria uma algo semelhante à "5+3", porém preciso transforma-la em um número (no caso, 8). Já tentei usar o (int) antes da string, porém nada.

Caso alguem possa me ajudar agradeço.

 

Observação: query() e row() funcionam de forma idêntica à mysql_query() e mysql_fetch_assoc().

Compartilhar este post


Link para o post
Compartilhar em outros sites

mostre como você fez.

Compartilhar este post


Link para o post
Compartilhar em outros sites
$slotquery = row(query("SELECT `attribute` FROM {{table}} WHERE id='{$userrow["slot1id"]}' LIMIT 1", "drops"));
$newvalue = eval($userrow["attack"] . $slotquery[1]["attribute"]);

query("UPDATE {{table}} SET `attack`='{$newvalue}' WHERE `uid`='{$userrow["id"]}';", "drops");

Compartilhar este post


Link para o post
Compartilhar em outros sites

do manual:

<?php
function matheval($equation) 
{
	$equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation); 
	// fix percentage calcul when percentage value < 10 
	$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation); 
	// calc percentage 
	$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation); 
	// you could use str_replace on this next line 
	// if you really, really want to fine-tune this equation 
	$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation); 
	if ( $equation == "" ) 
	{
		$return = 0; 
	} 
	else 
	{ 
		eval("\$return=" . $equation . ";" ); 
	}
	return $return; 
}


	$str = '3+5';
	echo matheval( $str );//saida: 8

http://php.net/eval

Compartilhar este post


Link para o post
Compartilhar em outros sites

Consegui resolver assim:


$slotquery = row(query("SELECT `attribute` FROM {{table}} WHERE id='{$userrow["slot1id"]}' LIMIT 1", "drops"));
eval("\$newvalue = {$userrow["attack"]}{$slotquery[1]["attribute"]};");

query("UPDATE {{table}} SET `attack`='{$newvalue}' WHERE `uid`='{$userrow["id"]}';", "drops");

 

Mas irei usar seu metodo também pois pelo que testei é muito bom..

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.