Home > Blockchain >  PHP: reading and parsing a nested JSON file
PHP: reading and parsing a nested JSON file

Time:05-16

I want to use a json file as a kind of database. In it I have categorized file names and now I want to read them via PHP.

{
"settings": {
  "prefix": "pix",
  "folder": "files/jpg",
  "delimiter": "-",
  "extension": "jpg"
},
"category": {
  "art": {
    "painting": {
      "1999": ["paint1","paint2","paint3"],
      "2000": ["paint4","paint5"]
    },
    "drawing": {
      "1995": ["sketch1","sketch2","sketch3"],
      "2012": ["sketch4","sketch5"]
    }
  },
  "project": {
    "website": {
      "2016": ["web1","web2","web3"]
    }
  }
}
}

This is how far I got:

$db = json_decode(file_get_contents("json/_database.json"), true);
$test1 = $db["category"]["art"]["painting"]["2000"];
var_dump($test1);

I would like to get the following data:

  1. get all category key names as an array: "art", "project"
  2. get all subcategory key names of 'art' as an array: "painting", "drawing"
  3. get all values from subcategory 'drawing' in the year 1995 as an array: "sketch1", "sketch2", "sketch3"

I know there are already questions about such problems, but I could not apply the answers to my case. I would be grateful for examples of syntax notation, which I can then adapt to other cases.

CodePudding user response:

1.:

array_keys($db["category"]);

2.:

array_keys($db["category"]["art"]);

3.:

array_values($db["category"]["art"]["drawing"]["1995"]);
  • Related