This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have json return:
{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }
How can I get value ItemSum by ItemID in php ?
How can I get value ItemSum by ItemID in php ?
You need to go through the items and look for the ItemID, e. g.:
$object = json_decode('{ "items": [ { "ItemID": 810, "ItemSum": 2 },
{ "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }');
function getSumbyID($object, $ID)
{
foreach ($object->items as $item) if ($item->ItemID == $ID) return $item->ItemSum;
}
echo getSumbyID($object, 902), "\n";
Like so:
$result = json_decode('{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }');
foreach($result->items as $item) {
var_dump($item->ItemSum);
}
Also, definitely read what's at the link #Paul Crovella commented with.
Related
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?
This question already has answers here:
Why is json_encode adding backslashes?
(7 answers)
Closed 4 years ago.
code:
$hyperlink = str_replace("%2F","","http://localhost/android/images/");
if($num>0)
{
$products_arr=array();
$products_arr["data"]=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$product_item=array(
"image_name" => $image_name,
"image_url" => $hyperlink.$file_s
);
array_push($products_arr["data"], $product_item);
}
echo json_encode($products_arr);
}
I have create a json file using php now I want to add hyperlink inside an array function. I am using str_replace("%2F","","http://localhost/android/images/"); but its not working and json file look like as mention below:
{
"data": [
{
"image_name": "cap-1",
"image_url": "http:\/\/localhost\/android\/images\/Cap-01.png"
},
{
"image_name": "cap-2",
"image_url": "http:\/\/localhost\/android\/images\/Cap-02.png"
},
{
"image_name": "cap-3",
"image_url": "http:\/\/localhost\/android\/images\/Cap-03.png"
},
{
"image_name": "ear-1",
"image_url": "http:\/\/localhost\/android\/images\/Ears-01.png"
},
{
"image_name": "ear-2",
"image_url": "http:\/\/localhost\/android\/images\/Ears-02.png"
},
{
"image_name": "ear-3",
"image_url": "http:\/\/localhost\/android\/images\/Ears-03.png"
},
{
"image_name": "hair-1",
"image_url": "http:\/\/localhost\/android\/images\/Hair Color-01.png"
},
{
"image_name": "hair-2",
"image_url": "http:\/\/localhost\/android\/images\/Hair Color-02.png"
}
]
}
So how can I remove "\" element from url? Please help me.
Thank You
Calling the option JSON_UNESCAPED_SLASHES within json_encode will fix your issue.
$example = json_encode($array, JSON_UNESCAPED_UNICODE |
JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
i'm using this API called "pollDaddy",
using php to retrieve json responses ..I've come across a little hiccup..
How do you get the total of each answer?
My json data:
{
"pdResponse": {
"partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301",
"userCode": "123456-FErKS5yu15scpSGmvip4JA==",
"demands": {
"demand": {
"result": {
"answers": {
"answer": [{
"text": "Yes",
"id": "23123124",
"total": "1074",
"percent": "89.13"
}, {
"text": "No",
"id": "23123125",
"total": "131",
"percent": "10.87"
}]
}, "id": "690432265"
}, "id": "GetPollResults"
}
}
}
}
First we have to decode the json data. so we use json_decode. Then we select the right element and loop through it to get all the anwers
$data = '{ "pdResponse": { "partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301", "userCode": "123456-FErKS5yu15scpSGmvip4JA==", "demands": { "demand": { "result": { "answers": { "answer": [{ "text": "Yes", "id": "23123124", "total": "1074", "percent": "89.13" }, { "text": "No", "id": "23123125", "total": "131", "percent": "10.87" }] }, "id": "690432265" }, "id": "GetPollResults" } } } }';
$response = json_decode($data);
$answers = $response->pdResponse->demands->demand->result->answers->answer;
foreach($answers as $a)
{
echo $a->total;
}
I have one json request which contain multiple array:
{
"user_type": "2",
"user_id": "57",
"client_detail": [
{
"server_user_id": "1",
........
........
"is_active": "1",
"client_local_id": "11"
},
{
"server_user_id": "2",
........
........
"is_active": "1",
"client_local_id": "12"
}
],
}
Using above request I change data into database. then return data from DB. but i have to pass client_local_id into response.
so suppose i got 3 result from DB then i have to return client_local_id(this field is not stored in DB, there is no need for that) with them. so i pass default client_local_id 0.
exa:
"client_detail": [
{
"server_user_id": "1",
........
........
"is_active": "1",
"client_local_id": 0
},
{
"server_user_id": "2",
........
........
"is_active": "1",
"client_local_id": 0
},
{
"server_user_id": "3",
........
........
"is_active": "1",
"client_local_id": 0
},
]
then using below code i change value of client_local_id.
$response = array('client_detail' => $dbvalue);
/* Change Client Local ID */
if(sizeof($client_detail_data)>0)
{
foreach($client_detail_data as $key=>$resclient_data) // loop of request
{
foreach($response['client_detail'] as $key1=>$res_client) //loop of response
{
//if id is match then change value
if($res_client['server_user_id']==$resclient_data['server_user_id'])
{
$response['client_detail'][$key1]['client_local_id'] = $resclient_data['client_local_id'];
}
}
}
}
But i think there is easy method, to do that. I have a multiple array in request so i don't want to use too much foreach loop. so how to solve it in proper way?
Thanks in advance.
First of all let’s map server_user_ids to client_user_ids:
$s2c = array();
foreach($resclient_data as $item) {
$s2c[$item['server_user_id']] = $item['client_user_id'];
}
Now we can use array_map directly on $response:
$response['client_detail'] = array_map(function($elem) use($s2c) {
$elem['client_local_id'] = $s2c[$elem['server_local_id']];
return $elem;
}, $response['client_detail']);
I diidn’t test the code, but hopefully the idea is clear.
Ok, so that title might be a little misleading, but I'm not quite sure what i'm describing, so here goes.
I have the following JSON :
{
"lastModified": 1368517749000,
"name": "Requiem Paradisum",
"realm": "Chamber of Aspects",
"battlegroup": "Misery",
"level": 25,
"side": 1,
"achievementPoints": 1710,
"emblem": {
"icon": 126,
"iconColor": "ffdfa55a",
"border": 3,
"borderColor": "ff0f1415",
"backgroundColor": "ff232323"
},
"news": [
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368482100000,
"itemId": 91781
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368477900000,
"itemId": 87209
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368475800000,
"itemId": 86880
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91781
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91779
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475320000,
"itemId": 91779
},
{
"type": "playerAchievement",
"character": "Osmoses",
"timestamp": 1368470700000,
"achievement": {
"id": 6193,
"title": "Level 90",
"points": 10,
"description": "Reach level 90.",
"rewardItems": [
{
"id": 87764,
"name": "Serpent's Heart Firework",
"icon": "inv_misc_missilelarge_green",
"quality": 1,
"itemLevel": 1,
"tooltipParams": {
},
"stats": [
],
"armor": 0
}
],
"icon": "achievement_level_90",
"criteria": [
],
"accountWide": false,
"factionId": 2
}
},
Basically i need to loop over everything in "news" and output it.
What I can't figure out how to parse it correctly :
A : without specifying key numbers and
B : when it gets to a key that then contains further keys and further arrays under those keys i'm at a loss. (E.g. the "player achievement" key)
I appreciate I'm probably being a bit newbie here and could quite possibly be on page 1 of "php for dummies" but i swear I've googled it to death!
See if this approach could fit. Be sure your JSON array is properly formatted though.
$test = the_json_array;
$array = json_decode($test,true);
function recursive($array) {
foreach($array as $key => $value) {
if (!is_array($value)) echo $key.":".$value."<br/>";
else recursive($value);
}
}
recursive($array);
SEE json_decode
Dont forget to give second argument as TRUE otherwise it will return object
and try something like this
$json = 'your json'
$json_array = json_decode($json,true);
$news = $json_array['news'];
foreach($news as $value)
{
print_r($value);
}
I think for your purpose you should have look at array_walk_recursive
function printResult($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($news, 'printResult');
yo need to do json_decode('your-jason', True) it will convert your Json string to Array.
Json_decode for more understanding
if you don't specify TRUE in jason_decode function then it will return php object
Hope answer the question. regards