0

On a game, there are three different teams. For example, team a, b, and c. On the game's database the playtime is reported like this: "[a,b,c]" and each letter is how many minutes the user has played on that specific team. I used PHP to grab the data from the database to display on a website, but it is just displaying as "[14,0,1]" as I have 14 minutes on team a, 0 on team b, and 1 on team c.

How can I format this, through PHP or JSON, to add a, b, and c, or in this case 14+0+1?

The code in PHP:

$sql = "SELECT * FROM players WHERE playerid ='". $steamprofile['steamid']  
."'";
$result = $db->query($sql);
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        $playtime = $row["playtime"];
    }

The code in HTML:

<span id="label">Playtime</span>: <b><span id="playerPlaytime"><?php echo 
$playtime; ?></span></b><br>

Output: http://prntscr.com/jum85v

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Max
  • 1

2 Answers2

1

Create an array by splitting on commas and then calculate the sum (trim extra stuff first):

$playtime = array_sum(explode(',', trim($row['playtime'], '"[]')));

To use JSON you still need to trim the quotes:

$playtime = array_sum(json_decode(trim($row['playtime'], '"')));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

If the variable from the DB is a string (it appears to be, perhaps, a JSON object), then in PHP you could do this:

$playtime = array_sum(json_decode($row['playtime']));
Kevin_Kinsey
  • 2,285
  • 1
  • 22
  • 23
  • If you want to do it in JSON, go here: https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers – Kevin_Kinsey Jun 13 '18 at 19:48