John Davidson

PHP: reading and parsing a nested JSON file

0 comments
Message:


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.



My Answer:
To achieve the desired results, you can use the following PHP code:

php
$db = json_decode(file_get_contents("json/_database.json"), true);

// Get all category key names as an array
$categoryKeys = array_keys($db["category"]);
var_dump($categoryKeys);

// Get all subcategory key names of 'art' as an array
$subcategoryKeys = array_keys($db["category"]["art"]);
var_dump($subcategoryKeys);

// Get all values from subcategory 'drawing' in the year 1995 as an array
$values = $db["category"]["art"]["drawing"]["1995"];
var_dump($values);


This code will output the following:

1. Array containing category key names: ["art", "project"]
2. Array containing subcategory key names of 'art': ["painting", "drawing"]
3. Array containing values from subcategory 'drawing' in the year 1995: ["sketch1", "sketch2", "sketch3"]

You can modify and adapt this code to access other data in your nested JSON file.

Rate this post

5 of 5 based on 6072 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us