Skip to content
Advertisement

Javascript browser game inventory system, checking if item is in characters JSON file

I’m new to programming and I’m learning by coding a simple incremental game. Currently I am working out the inventor system. I have a cooking skill in the game with a script that will take raw items and either cook or burn them based on chance.

I’m now trying to work out an inventory system to hold the items after the action. I have a character JSON file (linked to a firebase UID)

{
  "character":[
    {
    "Username"  :  "Tester01",
    "cooklvl"   :  "1",
    "cookxp"    :  "0"
}
],
"items" :[
{
"rf0000" : 0,
"rf0001" : 0,
"rf0002" : 0,
"rf0003" : 0,
"rf0004" : 0,
"rf0005" : 0,
"rf0006" : 0,
"rf0007" : 0
}
]
}

I want to add items to be stored here by ID using PHP to post them to my file server.

<?php 
$cookitem = $_POST['cookitem'];
$a = "../json/";
$b = $_POST['uid'];
$c = ".json";
$filename = $a.$b.$c;

$json_object = file_get_contents($filename);
$data = json_decode($json_object, true);
$data['cookitem'] = ++$cookitem;
$json_object = json_encode($data, JSON_NUMERIC_CHECK);
file_put_contents($filename, $json_object);

?>

I have this currently but I don’t want to have to add the items all at once and adjust quantity. I want to add and remove them dynamically with PHP.

So I would need to check something along the lines of: Does item”RF0051″ exist in playerdata.json? If no add it and set quantity to 1. If it does exist add 1 to the quantity.

How could I go about doing this in php? As well, is there a better way I could be going about this? The end goal is to have a fairly large amount of items. Am I shooting myself in the foot by pushing to JSON in terms of growth and server resources?

Advertisement

Answer

If you know what string to compare with, you can save it in a variable $yourString and then check with an if-statement if it exists:

 <?php
 $yourString = strtolower("RF0051");

 $json_object = file_get_contents($filename);
 $data = json_decode($json_object, true);

 if($data['items'][$yourString] != null){
    //It exists
 }

 ?>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement