How to parse second level of json php - php

I have a json like this:
[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]
I want to get in php each row for update my database. I don't know the number of second level json are. Sometimes will be 1, sometimes 2 and sometimes more.
I thought, I could read it doing something like this:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
//Bla bla
$i++;
}
I have used many times json file in php but always, just one level. This is my first time with more than one.
But I can't. I know, because I checked, that in $json I have the complete json file.

You need to reference the subkey in your array:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
echo $json_post[$i]["a"];
// or
echo $json_post[$i][0];
$i++;
}
More docs can be found here: http://php.net/manual/en/language.types.array.php
And a similar question here: PHP reference specific key and value within multidimensional array

i'd use foreach:
foreach($json_post as $key => $value) {
echo $value;
}

$j = '[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]';
$decoded = json_decode($j, true);
//var_dump($decoded);
foreach ($decoded as $key => $post) {
$valueOfA = $post['a'];
$valueOfB = $post['b'];
}

Related

How do I get a count of how many times a certain number is inside of a json file using php?

Here is what my data.json file consists of:
[
{
"roles":[
"848173029280055326"
],
"nick":null,
"avatar":null,
"premium_since":null,
"joined_at":"2021-05-29T12:15:32.907000+00:00",
"is_pending":false,
"pending":false,
"user":{
"id":"848088079562571797",
"username":"E. Gadd",
"avatar":"9992dc24217be555eae9dfe1c9960b0e",
"discriminator":"6174",
"public_flags":64
},
"mute":false,
"deaf":false
},
{
"roles":[
"848173029280055326"
],
"nick":null,
"avatar":null,
"premium_since":null,
"joined_at":"2021-05-29T12:15:32.907000+00:00",
"is_pending":false,
"pending":false,
"user":{
"id":"848088079562571797",
"username":"E. Gadd",
"avatar":"9992dc24217be555eae9dfe1c9960b0e",
"discriminator":"6174",
"public_flags":64
},
"mute":false,
"deaf":false
}
]
And here is what my php code looks like:
<?php
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);
$total = 0;
foreach ($data["roles"] as $value) {
if($value["roles"]==848173029280055326){
$total = $total+1;
}
}
echo $total;
?>
I can't seem to get a total of how many times 848088079562571797 appears inside of the json file. I always seem to get this error
Warning: Undefined array key "roles" in C:\xampp\htdocs\filterjson.php on line 5
Warning: foreach() argument must be of type array|object, null given in C:\xampp\htdocs\filterjson.php on line 5
0
May I have some help please? Thank you.
The actual simplest way is converting the json to a string and then use substr_count.
$jsonData = file_get_contents("data.json");
$role = '848173029280055326';
$count = substr_count($jsonData, $role)
$count will be the number of times it is in your json
The loop should look something like:
foreach ($data as $value){...}
Also, as it looks like you might have multiple roles (you made an "array" in the json, by putting them in squared brackets), just iterate over all of them:
for ($i = 0; $i < count($value["roles"]); $i++){
if($value["roles"][0]==848173029280055326){
$total = $total+1;
}
}
This should easily resolve your problem. I tried it and it worked.
You need to change
foreach ($data["roles"] as $value) {
to
foreach ($data as $value) {
because your json structure is an array of objects

php filtering json file and returning an attribute value

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",
}
]
]
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'];
I tried with your sample JSON.
First, json_decode will return a PHP array to use foreach on it. I wrote a simple foreach and checked your searching ID is equal to element's datasetID. If it is equal this is the datasetName you are searching for.
<?php
$json = '[[{"datasetID":"5fd4124900827","institutionCode":"None","collectionCode":"None","datasetName":"None"}],[{"datasetID":"5fd4058e5c8d2","institutionCode":"None","collectionCode":"None","datasetName":"None"}]]';
$elements = json_decode($json,TRUE);
$searchingID = "5fd4058e5c8d2";
foreach ($elements as $element) {
if(isset($element[0]['datasetID']) && $element[0]['datasetID'] == $searchingID){
$filtered_data = $element[0];
break;
}
}
echo $filtered_data['datasetName']; // or return $filtered_data['datasetName'];
?>

PHP/MYSQL: Access data in Array of Dictionaries

I receive a JSON stream from an iphone that contains some simple strings and numbers as well as an array of dictionaries. I would like to work with these dictionaries, in essence, storing the data in each of them in a separate MYSQL record.
To get access to the strings as well as the array from the JSON stream, I am using the following:
$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($jsonString, true);
$authString = jsonArray['authstring'];
$itemsArray = $jsonArray['itemsArray'];
This is what itemsArray looks like before being sent to the server:
itemsArray = (
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 6;
iid = 0;
title = "test";
complete = 1;
userid = 99;
whenaddedstr = "2018-06-21 14:10:23";
},
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 37;
iid = 0;
title = "how about this";
userid = 88;
whenaddedstr = "2018-07-07 16:58:31";
},
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 38;
iid = 0;
title = reggiano;
userid = 1;
whenaddedstr = "2018-07-07 17:28:55";
}
etc.
I guess I should probably put these dictionaries into an Associative Array in order to save them.
I am struggling, however, with how to reference and get the objects. From what I can tell the following code is returning empty values in so far as $message comes back as empty.
$anitem = $jsonArray['itemsArray'][0];
$message=$anitem;
$title = $jsonArray['itemsArray'][0].[item];
$message.=$title;
Can anyone suggest proper syntax to grab these items and their properties?
Thanks in advance for any suggestions.
I find it strange that people associate things with a dictionary, while it is nothing more then a multidimensional array.
If you can read JSON, you see that the variable will have an index containing each entry.
For PHP:
foreach($jsonArray as $array){
// note that $array is still an array:
foreach($array as $v){
echo "Hurray!: '$v'";
}
}
If it really was an object (or cast to an object), the only thing you need to change is how you access the variable (as in any other language). In PHP it would be:
echo $jsonArray[0]->lasttouchedstr;
Or of it was the same loop:
foreach($jsonArray as $v){
echo $v->lasttouchedstr;
}
Multidimensional?
echo $jsonArray['itemsArray'][0][item]; // array
echo $jsonArray->itemsArray[0][item]; // if items array is an actual array and jsonArray an object.
Most languages associate things written as a . that the left side is an object. In PHP it's written as ->.

Parsing JSON in for each with increment PHP

I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}

json decode with an array in php

I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.
If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}

Categories