I have a json file which I read in. I want to first filter the json data to return the object defined by the datasetID, then get out the datasetName. I have filtered in javascript, but would prefer to stay in php but I can’t figure it out, any ideas?
note: foreach
is not required as only a single record is returned when filtered using the datasetID. So rather than using a foreach
method how would you swelect a single record, first
for instance?
$datasetID = '5fd4058e5c8d2'; // unique 13 character string $data = json_decode(file_get_contents(path/to/file), True);
So I need to first filter for the unique object with $datasetID = ‘5fd4058e5c8d2’;
$filtered_data =
Then I need to return the attribute datasetName from that object
$datasetName =
pointers to the best ways to do this is welcomed.
Sample json data:
[ [ { "datasetID":"5fd4124900827", "institutionCode":"None", "collectionCode":"None", "datasetName":"None" } ], [ { "datasetID":"5fd4058e5c8d2", "institutionCode":"None", "collectionCode":"None", "datasetName":"None", } ] ]
Advertisement
Answer
I don’t know how you got that JSON but it is nested deeper than needed. You can merge the top level arrays to flatten it, then index on datasetID
:
$data = array_merge(...$data); $filtered_data = array_column($data, null, 'datasetID')[$datasetID]; $datasetName = $filtered_data['datasetName'];
Shorter:
$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$datasetID]; $datasetName = $filtered_data['datasetName'];
Or to keep them all to use:
$data = array_column(array_merge(...$data), null, 'datasetID'); $datasetName = $data[$datasetID]['datasetName'];