0

I am new in PHP and I have a tutorial but I really no idea how to do it.

I have a Package table and I want to get the Items Name from the ID. Is it possible to get the Item name from the JSON file? If yes how should I do it?Thanks in advance.

Table:

Package Items Names
1 (Here show the Items name in the package)
2 (e.g: Clothes & Necklace)

JSON file:

{
    "Package_01": {
        "Item_01": {
            "Name": "Perfume",
        },
        "Item_02": {
            "Name": "Clothes",
        } 
    },
    "Package_02": {
        "Item_02": {
            "Name": "Clothes",
        },
        "Item_03": {
            "Name": "Necklace",
        }
    }
}
LJ27
  • 109
  • 2
  • 15
  • *Is it possible to get the Item name from the JSON file* What do you mean? – Wahyu Kristianto Mar 06 '22 at 21:27
  • 1
    Have you read the documentation? https://www.php.net/manual/en/function.json-decode.php – kmoser Mar 06 '22 at 21:27
  • 1
    This will teach you everything you need to know for this task (and more besides): [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) – ADyson Mar 06 '22 at 21:40

1 Answers1

0

First of all you have to decode the json file, you can use the PHP function json_decode($filename) ($filename is the var you assigned to contain the json). let's name your file $jsonFile:

$file = json_decode($jsonFile);.

what the function does is tranform the json to php Object and then you can access it's elements as you would with a php object : for example, to get the name of Item one you'd have to do this :

 $jsonFile = {
"Package_01": {
    "Item_01": {
        "Name": "Perfume",
    },
    "Item_02": {
        "Name": "Clothes",
    } 
},
"Package_02": {
    "Item_02": {
        "Name": "Clothes",
    },
    "Item_03": {
        "Name": "Necklace",
    }
}
};
$file = json_decode($jsonFile);
$itemName = $file->Package_01->Item_01->Name;

if you var_dump $itemName you should be getting "Perfume". You can also get all item names in a package or in all packages using foreach. hit me up if you need more help.

IceCold
  • 35
  • 4