This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 months ago.
I've been trying to find ways to print the individual data but can't seem to figured out where I'm going wrong.
I started with this but I get no results. Before this I tried nesting loops but also got nowhere either.
$data = curl_exec($ch);
$d = json_decode($data, true);
foreach($d as $k=>$v){
echo $v['value']['displayName'];
}
Then I tried the following with only got me some of the results. I'm not sure where I'm going wrong with this.
foreach(json_decode($data,true) as $d){
foreach($d as $k=>$v){
foreach($v as $kk=>$vv){
echo $kk.$vv;
}
}
}
The JSON looks like the following:
{
"value": [
{
"id": "",
"name": "",
"etag": "",
"type": "Microsoft.SecurityInsights/alertRules",
"kind": "Scheduled",
"properties": {
"incidentConfiguration": {
"createIncident": true,
"groupingConfiguration": {
"enabled": false,
"reopenClosedIncident": false,
"lookbackDuration": "PT5M",
"matchingMethod": "AllEntities",
"groupByEntities": [],
"groupByAlertDetails": null,
"groupByCustomDetails": null
}
},
"entityMappings": [
{
"entityType": "Account",
"fieldMappings": [
{
"identifier": "FullName",
"columnName": "AccountCustomEntity"
}
]
},
{
"entityType": "IP",
"fieldMappings": [
{
"identifier": "Address",
"columnName": "IPCustomEntity"
}
]
}
],
"queryFrequency": "P1D",
"queryPeriod": "P1D",
"triggerOperator": "GreaterThan",
"triggerThreshold": 0,
"severity": "Medium",
"query": "",
"suppressionDuration": "PT1H",
"suppressionEnabled": false,
"tactics": [
"Reconnaissance",
"Discovery"
],
"displayName": "MFA disabled for a user",
"enabled": true,
"description": "Multi-Factor Authentication (MFA) helps prevent credential compromise. This alert identifies when an attempt has been made to diable MFA for a user ",
"alertRuleTemplateName": null,
"lastModifiedUtc": "2022-11-14T02:20:28.8027697Z"
}
},
...
...
...
Here is how you can get the display name without a loop. Notice that the 0 is the key value of the array since it doesn't have a name.
We start from the value, and we move one layer deeper by selecting the first array 0. Now we need to select the properties and finally, we can get the displayName from there.
$displayName = $d["value"][0]["properties"]["displayName"];
echo($displayName);
/*
Here is a quick demonstration:
value:
{
0:
{
...
properties:
{
...
displayName: [We made it!]
}
}
}
*/
And here is a very good post that explains this in more detail
How to decode multi-layers nested JSON String and display in PHP?
Related
I am programming a adminpanel with charts etc. Now I want to access a collection but before i can do that I need to know the name of the collection. So I can use that in the method itself
this is the snippet
{
"335": [],
"338": [
{
"id": 114,
"uuid": "",
"creator": null,
"ip": "",
"version": 338,
"time": "1526806163720"
},
{
"id": 115,
"uuid": "",
"creator": null,
"ip": "",
"version": 338,
"time": "1526806269412"
}
],
"340": [],
"389": [],
"393": [],
"401": [],
"404": []
}
As you can see every collection that is in this collection has a name.
When I am using this piece of code it doesnt give me a way to get to the name to use it in the switch statement.
foreach ($toConvert as $convert) {
switch ($convert) {
Does anyone know if this can be done or is this a limitation of laravel 5.7?
Use:
foreach ($toConvert as $name => $convert) {
switch ($name) {
...
The second form will additionally assign the current element's key to the $key variable on each iteration.
You can read more here: http://php.net/manual/en/control-structures.foreach.php
My json file look likes
myjson.json
[
{"name":"category_01","data":
[
{"id":"1","word":"ma","given_value":"1"},
{"id":"3","word":"me","given_value":"1"},
] }
[
{"name":"category_02","data":
[
{"id":"1","word":"vea","given_value":"1"},
{"id":"3","word":"ve","given_value":"1"},
] }
So what I want here is, check whether a particular value is in this json array using php. Assume that,
myphp.php
$word = 've';
if this value is in the above array, should find is it in category_01 or category_02. and also want to find given_value of matching word.
I just tried in this way,
$data = file_get_contents ("myjson.json");
$json = json_decode($data, true);
foreach($arr as $item) {
$uses = ($item['word']= $word);
}
This doesn't work. How can I fix this, Please help me!
First of all, the JSON you posted is invalid. I think it should look like this:
[
{
"name": "category_01",
"data": [{
"id": "1",
"word": "ma",
"given_value": "1"
},
{
"id": "3",
"word": "me",
"given_value": "1"
}
]
},
{
"name": "category_02",
"data": [{
"id": "1",
"word": "vea",
"given_value": "1"
},
{
"id": "3",
"word": "ve",
"given_value": "1"
}
]
}
]
Try using on online tool like https://jsonlint.com/ to check your JSON. (if you get errors i recommend build the json again from scratch).
I also recommend checking your json before using it:
if ($arr === null && json_last_error() !== JSON_ERROR_NONE) {
die("incorrect json data");
}
To get your value you have to KNOW how your data looks like and then process it:
foreach($arr as $category) {
foreach($category['data'] as $data) {
if(strstr($data['word'], $word))
echo $category['name'].' '.$data['word'].' '.$data['given_value']."\n";
}
}
I have JSON data which follows this model:
{
"questions": [
{
"questionKey": 0,
"question": "string",
"required": true,
"type": "multipleChoice",
"maxSize": 0,
"answers": [
{
"answer": "string",
"answerKey": 0
}
]
}
],
"fields": [
{
"field": "string",
"answers": [
"string"
],
"required": true,
"maxSize": 0
}
]
}
I am having difficult getting all the fields > field values. When i do a var_dump($jsondata) it is printing all the data so I know I am getting and storing the data ok. I know I need to do a foreach statement like:
foreach ($jsondata as $data) {
echo $data['fields'];
}
I know this is wrong but I don't know how to cycle through all the fields > field values. Your help is much appreciated :)
Try something like this:
//Decode JSON string into a PHP array.
$jsonData = json_decode($jsonStr, true);
//Loop through it like any associative array.
foreach($jsonData['fields'] as $field){
var_dump($field);
echo $field['field'] , '<br>';
}
I really need help on this one.
I have the following Json Schema:
{
"url": "http://www.google.com",
"bodySchema": {
"type": "object",
"properties": {
"SKU": {
"sync": "True",
"mapTo": "SKU",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"mapTo": "",
"type": "integer"
},
"Stock": {
"sync": "True",
"mapTo": "Stock",
"type": "integer"
}
},
"required": {
"0": "SKU",
"1": "Stock"
}
}
}
I would like to retrieve all elements and check if they are required or not,
On the first part (Getting all elements)
What I'm doing is:
foreach ($this->methods as $data) {
if(!empty($data['bodySchema']->properties)){
}
}
But my problem is that I have no way to get the SKU, WarehouseID or Stock, because it's not a key nor anything of the kind.
For my second issue what I was thinking, was to put all required as string and do a loop through them, but if there is any alternative would be glad to know.
You can get the properties out with a simple loop:
foreach ($data->bodySchema->properties as $key => $value) {
// ..
}
If you want to add the required field to the results from above, you can do it like so:
foreach ($data->bodySchema->required as $required) {
$data->bodySchema->properties->$required->required = true;
}
Example with objects or with arrays.
I'm trying to use some JSON data in my website, but i got stuck while trying to read from.
Getting the data works well:
<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'));
?>
this is a little excerpt of the JSON data, but it lasts out to explain the problem
{
"type": "champion",
"format": "standAloneComplex",
"version": "5.10.1",
"data": {
"Aatrox": {
"version": "5.10.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "Die Klinge der Düsteren",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
},
"Ahri": {
"version": "5.10.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "Die neunschwänzige Füchsin",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
},
}
}
Question: How is it possible, to access the value of "key", without knowing the 'heading' (e.g. "Aatrox") ?
I tried $data->{'data'}[0]->{'key'}, but that doesn't work.
Second Question: I also tried to search for the value of "key", but had no success in building the path with this method in PHP. A try with JavaScript worked well, but I would prefer to have a server-sided solution.
Thanks for your help!
If you want an element at particular 'offset', use
array_values($data->data)[0]->key;
otherwise, use foreach:
foreach ($data->data as $heading=>$data) {
echo "The heading is $heading and key is {$data->key}";
}
Alternative very short way:
<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'), true);
$first = current($data['data']);
More complete example:
<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'));
$key = current($data->data)->key
Personally I prefer to convert JSON object into the more PHP friendly Array.
If you use json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')));
You will be able to access the key value with something like this
$champions = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')));
foreach($champions['data'] as $key => $row){
echo $row['key'];
}
This will echo your keys.