1

I'm new to PHP.

My code reads a price value from a Steam game's json data.

http://store.steampowered.com/api/appdetails/?appids=8870

Problem is that the value of the price node is not formatted with a comma separator for dollars and cents. My code works to piece together the dollars and cents but is it the right way to do it for this instance. Also if there is another easier method of doing my newbie code, feel free to show me where it can be improved. Thanks!

<?php

$appid = '8870';

$ht = 'http://store.steampowered.com/api/appdetails/?appids=' . $appid;

$fgc = file_get_contents($ht);
$jd = json_decode($fgc, true);

$gdata = $jd[$appid]['data'];

$gname = $gdata['name'];
$gprice = $gdata['price_overview']['final'];
$gdesc = $gdata['detailed_description'];

$gusd = substr($gprice, 0, -2);
$gcent = substr($gprice, 2);

echo $gname. '<br>';
echo 'Price: $' .$gusd. ',' .$gcent;

?>

If I may ask another question... can the price data aka $gprice be added to another price data that is fetched, to return a total.

4

2 回答 2

1

我基本上会做你正在做的事情,只是除以 100 更简单:

将价格变成浮动价格:

$gprice = $gprice / 100;

然后使用money_format

参考:PHP 文档 - money_format

您也可以这样做,但实际上没有必要。

$gprice = (int) $gdata['price_overview']['final'];
于 2013-04-27T22:06:13.510 回答
0

转换还不错,但您也可以使用它:

$gusd = $gprice/100;

echo $gname. '<br>';
echo 'Price: $' .str_replace('.', ',', $gusd);

或者使用money_format而不是replace,但它有点复杂。

此外,要添加另一个,您可以只使用 + 或 += 运算符,如下所示:

$gprice+= $gdata['price_overview']['final'];
于 2013-04-27T22:12:37.620 回答