0

I have a file called data.txt in the public path , it has this

{"data":[{"name": "Jack", "age": 13},{"name": "Mary", "age": 15}]}

and I want to read these data and also return the age for both Jack and Mary,

I know that I can read the file using the decode_json(file_get_contents) but I have no clue how to fetch the data and return specific records from it.

Any help is much appreciated !

1 Answer 1

3

You can load the file and decode the content with:

$content = json_decode(file_get_contents($path), true);

This will give you the associative array that contains your JSON content.

You can access data in user objects like that:

$userData = $content['data']; // content of "data" field
$jackData = $userData[0]; // first object in "data" array - Jack
$jackName = $jackData['name']; // Jack's name
Sign up to request clarification or add additional context in comments.

2 Comments

I fixed one typo (missing $ - that's something your IDE should detect), apart from that the code works
yes i already know about the typo and fixed it, also the array inside json file was missing a '}' at the end of it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.