In a PHP script that I'm writing I need to extract some massive JSON files and parse through them to retrieve a single value for each top level object.
My JSON file looks something like this:
[
{
"SOMEDATA": "SOMEVALUE",
"MOREDATA": "MOREVALUES",
"METADATA": {
"CUSTOM": {
"TYPE": "THE VALUE THAT I NEED",
//...more irrelevant data
},
//...more irrelevant data
},
//...more irrelevant data
},
... Repeats several thousand times.
]
The only piece of data that I want right now is the TYPE, which is buried several layers down. What I want to know is if there's a way that I can extract all of those TYPEs into an array using some built in PHP functionality. I've been doing it the long way of just looping through every top level index in the JSON file, but I feel like there's probably a better way to do this. Right now I'm bench marking at over a minute for execution, which is a little painful since this is for a small web application that will be getting accessed frequently.
If there is no built in functions that I can use to achieve this result of:
[
0 => "TYPE1",
1 => "TYPE2",
2 => "TYPE3",
3 => "TYPE4",
...
]
is there some internal pointers or anything to PHP objects I can use to do this faster than just looping through the array?
I would normally just write the parsed array to a new file as a cron job every so often, and just grab data from the already parsed file, which would be much faster, but the JSON file changes too frequently to be able to justify this approach.
Note: I could do this with array_walk and form the new array in the callback, as suggested by some other answers, but internally that's still a loop. I want to know if there's a way to do this that in the backend takes advantage of pointer and array internals to optimize the performance. Unless in an interpreted language that isn't possible, I don't know how much PHP is able to optimize code on the fly. I'm relatively new to PHP, so I'm unsure what it's capable of.