getting Notice: Undefined index: with use of json_decode [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
I am new in PHP. I am trying to get some value from json file and following
This Stackoverflow answer
When I run example given in answer working fine.
I have my.json file like below
{
"quoteSummary": {
"result": [
{
"summaryDetail": {
"maxAge": 1,
"priceHint": {
"raw": 2,
"fmt": "2",
"longFmt": "2"
},
"previousClose": {
"raw": 126,
"fmt": "126.00"
},
"navPrice": {},
"currency": "USD",
"fromCurrency": null,
"toCurrency": null,
"lastMarket": null,
"volume24Hr": {},
"volumeAllCurrencies": {},
"circulatingSupply": {},
"algorithm": null,
"maxSupply": {},
"startDate": {},
"tradeable": false
},
"defaultKeyStatistics": {
"maxAge": 1,
"priceHint": {
"raw": 2,
"fmt": "2",
"longFmt": "2"
},
"lastDividendDate": {
"raw": 1612483200,
"fmt": "2021-02-05"
},
"lastCapGain": {},
"annualHoldingsTurnover": {}
},
"earnings": {
"maxAge": 86400,
"earningsChart": {
"quarterly": [
{
"date": "1Q2020",
"actual": {
"raw": 0.64,
"fmt": "0.64"
},
"estimate": {
"raw": 0.56,
"fmt": "0.56"
}
},
{
"date": "2Q2020",
"actual": {
"raw": 0.64,
"fmt": "0.64"
},
"estimate": {
"raw": 0.51,
"fmt": "0.51"
}
}
],
"currentQuarterEstimate": {
"raw": 0.98,
"fmt": "0.98"
},
"currentQuarterEstimateDate": "1Q",
"currentQuarterEstimateYear": 2021,
"earningsDate": [
{
"raw": 1619568000,
"fmt": "2021-04-28"
},
{
"raw": 1620000000,
"fmt": "2021-05-03"
}
]
},
"financialsChart": {
"yearly": [
{
"date": 2017,
"revenue": {
"raw": 229234000000,
"fmt": "229.23B",
"longFmt": "229,234,000,000"
},
"earnings": {
"raw": 48351000000,
"fmt": "48.35B",
"longFmt": "48,351,000,000"
}
},
{
"date": 2018,
"revenue": {
"raw": 265595000000,
"fmt": "265.6B",
"longFmt": "265,595,000,000"
},
"earnings": {
"raw": 59531000000,
"fmt": "59.53B",
"longFmt": "59,531,000,000"
}
},
{
"date": 2019,
"revenue": {
"raw": 260174000000,
"fmt": "260.17B",
"longFmt": "260,174,000,000"
},
"earnings": {
"raw": 55256000000,
"fmt": "55.26B",
"longFmt": "55,256,000,000"
}
},
{
"date": 2020,
"revenue": {
"raw": 274515000000,
"fmt": "274.51B",
"longFmt": "274,515,000,000"
},
"earnings": {
"raw": 57411000000,
"fmt": "57.41B",
"longFmt": "57,411,000,000"
}
}
],
"quarterly": [
{
"date": "1Q2020",
"revenue": {
"raw": 58313000000,
"fmt": "58.31B",
"longFmt": "58,313,000,000"
},
"earnings": {
"raw": 11249000000,
"fmt": "11.25B",
"longFmt": "11,249,000,000"
}
},
{
"date": "2Q2020",
"revenue": {
"raw": 59685000000,
"fmt": "59.69B",
"longFmt": "59,685,000,000"
},
"earnings": {
"raw": 11253000000,
"fmt": "11.25B",
"longFmt": "11,253,000,000"
}
},
{
"date": "3Q2020",
"revenue": {
"raw": 64698000000,
"fmt": "64.7B",
"longFmt": "64,698,000,000"
},
"earnings": {
"raw": 12673000000,
"fmt": "12.67B",
"longFmt": "12,673,000,000"
}
},
{
"date": "4Q2020",
"revenue": {
"raw": 111439000000,
"fmt": "111.44B",
"longFmt": "111,439,000,000"
},
"earnings": {
"raw": 28755000000,
"fmt": "28.75B",
"longFmt": "28,755,000,000"
}
}
]
},
"financialCurrency": "USD"
}
}
],
"error": null
}
}
I am trying to run like below
$json = file_get_contents('my.json');
$data = json_decode($json, true);
echo $data['quoteSummary']['result']['summaryDetail']['priceHint']['raw'];
but its giving me warning like
Notice: Undefined index: summaryDetail in C:\xampp\htdocs\index.php on line 6
Basically I am looking for get below values from my json file
From summaryDetail, I want
maxAge
priceHint->raw
From defaultKeyStatistics, I want
lastDividendDate->raw
and From Earning, I want
earningsChart->quarterly->actual->raw
Let me know if anyone can help me for same. I am trying from last hour but not able to get idea what I should do .
Thanks!

Your result node is an array of objects, so it be probably:
echo $data['quoteSummary']['result'][0]['summaryDetail']['priceHint']['raw'];

Related

How to access JSON object values using vue steps?

This is step 1. These are the input boxes i want to type. This is the function I created to point each value to input boxes:
getmyEditor: function(){
this.chartType = this.options.chart.type;
this.backgroundColor = this.options.chart.backgroundColor;
this.borderColor = this.options.chart.borderColor;
this.borderWidth = this.options.chart.borderWidth;
this.height = this.options.chart.height;
this.options.xAxis.plotLines = [{
value: this.xPlotLinesvalue,
label: {
text: this.xPlotLinesText,
align: 'center',
style: {
color: 'gray'
}
}}];
Above code i created to access object values. how to apply this values added
text boxes?
{"chart": {
"type": "pie",
"backgroundColor": "#FFFFFF",
"borderColor": "#000",
"borderWidth": 0,
"height": 300,
"inverted": false,
"plotBackgroundColor": "#FFFFFF",
"plotBorderColor": "#FFFFFF",
"plotBorderWidth": 1,
"style": {
"fontFamily": "Open Sans"
},
"polar": ""
},
"title": {
"text": "Title",
"x": -20
},
"table": {
"text": ""
},
"xAxis": {
"max": null,
"categories": [],
"title": {
"text": ""
},
"plotLines": [
{
"value": 0,
"width": 0,
"color": "red",
"label": {
"text": "",
"align": "center",
"style": {
"color": "gray"
}
}
}
]
},
"yAxis": {
"title": {
"text": ""
},
"categories": [],
"min": null,
"max": null,
"plotLines": [
{
"value": 0,
"width": 0,
"color": "red",
"label": {
"text": "",
"align": "center",
"style": {
"color": "gray"
}
}
}
]
},
"zAxis": "",
"tooltip": {
"valueDecimals": 0,
"valuePrefix": "",
"valueSuffix": "",
"padding": 8
},
"legend": {
"enabled": true,
"layout": "vertical",
"align": "right",
"verticalAlign": "middle",
"borderWidth": 0
},
"credits": {
"enabled": false
},
"plotOptions": {
"series": {
"color": "#582b6e",
"stacking": "",
"point": {
"events": {}
}
},
"scatter": {
"marker": {
"radius": 4,
"states": {
"hover": {
"enabled": true,
"lineColor": "rgb(100,100,100)"
}
}
},
"states": {
"hover": {
"marker": {
"enabled": false
}
}
},
"tooltip": {
"headerFormat": "<b>{series.name}</b><br>",
"pointFormat": "{point.x} , {point.y} ",
"x_unit": "",
"y_unit": ""
}
}
},
"series": [
{
"name": "Brands",
"colorByPoint": true,
"data": [
{
"name": "IE",
"y": 56.33
},
{
"name": "Chrome",
"y": 24.03,
"sliced": true,
"selected": true
},
{
"name": "Firefox",
"y": 10.38
},
{
"name": "Safari",
"y": 4.77
},
{
"name": "Opera",
"y": 0.91
},
{
"name": "Other",
"y": 0.2
}
]
}
],
"lang": {
"noData": "NO DATA AVAILABLE!"
},
"noData": {
"style": {
"fontWeight": "bold",
"fontSize": "15px",
"color": "#303030"
}
}
}
I'm trying to access (point to text boxes) this object using vue, but it's not working yet. How to do that correctly? I point each object value using this vue function inside method.
This is i want final output: This object view inside textarea if i change text area object value then that value will going to above input boxes.

Using PHP, how can i find the number of occurences of the [departs_at] field?

{
"currency": "USD",
"results": [
{
"itineraries": [
{
"outbound": {
"duration": "08:35",
"flights": [
{
"departs_at": "2018-07-03T18:35",
"arrives_at": "2018-07-03T21:15",
"origin": {
"airport": "BOS",
"terminal": "A"
},
"destination": {
"airport": "YHZ"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "3713",
"aircraft": "DH4",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 5
}
},
{
"departs_at": "2018-07-03T22:20",
"arrives_at": "2018-07-04T08:10",
"origin": {
"airport": "YHZ"
},
"destination": {
"airport": "LGW",
"terminal": "N"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "24",
"aircraft": "7M8",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 1
}
}
]
}
}
],
"fare": {
"total_price": "653.40",
"price_per_adult": {
"total_fare": "653.40",
"tax": "178.40"
},
"restrictions": {
"refundable": true,
"change_penalties": true
}
}
},
This is json data fetched from live flights query. I want to be able to determine the number of stops for each flight using the [depart_at] field. So I have been struggling to get the number of occurrences of the [depart_at] field so as to derive how many stops(layovers) for each flight. I have already converted to php using the code below: But I am not getting the count.
<?php foreach ($itinerary['outbound']['flights'] as $flight ){
echo count($flight['flights']);
}?>
You can try like this:
$json = '{
"currency": "USD",
"results": [
{
"itineraries": [
{
"outbound": {
"duration": "08:35",
"flights": [
{
"departs_at": "2018-07-03T18:35",
"arrives_at": "2018-07-03T21:15",
"origin": {
"airport": "BOS",
"terminal": "A"
},
"destination": {
"airport": "YHZ"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "3713",
"aircraft": "DH4",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 5
}
},
{
"departs_at": "2018-07-03T22:20",
"arrives_at": "2018-07-04T08:10",
"origin": {
"airport": "YHZ"
},
"destination": {
"airport": "LGW",
"terminal": "N"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "24",
"aircraft": "7M8",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 1
}
}
]
}
}
],
"fare": {
"total_price": "653.40",
"price_per_adult": {
"total_fare": "653.40",
"tax": "178.40"
},
"restrictions": {
"refundable": true,
"change_penalties": true
}
}
}';
echo substr_count($json, 'departs_at');
You can try that way.
$countDepartsAt = 0;
foreach ($itinerary['outbound']['flights'] as $flight ){
if(array_key_exists('departs_at', $flight)) {
$countDepartsAt++;
}
}
echo $countDepartsAt;

How to JSON with duplicate 'id' values?

I am receiving data from another site with json API.
how can I get the data of the objects with the same id number.
I try as follows but it turns blank..
there are 10 objects with the same id number
how can i get them.
The typeid number is the same but the specialvalue value is different.
{"id":4620041,"active":true,"typeid":56,"specialvalue":"0.5","fields":{"magic":{"active":true,"type":"magic","value":"1.05"},"xmagic":{"active":true,"type":"xmagic","value":"7.5"}}}
{"id":4620045,"active":true,"typeid":56,"specialvalue":"1.5","fields":{"magic":{"active":true,"type":"magic","value":"3.05"},"xmagic":{"active":true,"type":"xmagic","value":"3.5"}}}
if($test->typeid =="56")
{
if (specialvalue == "0.5") {
$alta = $test->fields->magic->value;
$uste = $test->fields->xmagic->value;
}
}
echo $alta - $uste ;
Thank you in advance for your help
https://i.hizliresim.com/Pl0LL7.jpg
Few observations :
Provided JSON is not a valid JSON.
It should be an array of objects to filter the specific data as per the requirement.
Solution :
let jsonObj = [{
"id": 5246752,
"active": true,
"typeid": 56,
"specialvalue": "0.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "1.06"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "7.0"
}
}
}, {
"id": 5246753,
"active": true,
"typeid": 56,
"specialvalue": "1.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "1.35"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "3.0"
}
}
}, {
"id": 5246754,
"active": true,
"typeid": 56,
"specialvalue": "2.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "2.0"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.7"
}
}
}, {
"id": 5246755,
"active": true,
"typeid": 56,
"specialvalue": "3.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "3.45"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.25"
}
}
}, {
"id": 5246756,
"active": true,
"typeid": 56,
"specialvalue": "4.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "6.25"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.08"
}
}
}, {
"id": 5246757,
"active": true,
"typeid": 56,
"specialvalue": "5.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "9.5"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.02"
}
}
}];
let filteredData = jsonObj.filter(item => item.typeid===56 && item.specialvalue==="0.5");
console.log(filteredData);
Use .filter
var filteredData = data.filter(
(el) => {
return el.typeid===56 && el.specialvalue==="0.5";
}
);
This will return only those elements with el.typeid===56 && specialvalue==="0.5"

Elastic Range Search Failure

My range filter keeps failing on my windows elastic 1.4 instance. It gives no error just returns no records.
PUT reseller_api_logging
{
"mappings": {
"record": {
"properties": {
"PastelAccountNumber": { "type": "string" },
"CreatedAt": { "type": "date" ,"format":"yyyy-MM-dd HH:mm:ss" },
"HTTPmethod": { "type": "string" },
"ContentTypeRequest": { "type": "string" },
"Endpoint": { "type": "string" },
"RequestParams": { "type": "string" , "index": "not_analyzed" },
"RawResponse": { "type": "string" , "index": "not_analyzed" },
"Response": { "type": "string" , "index": "not_analyzed" }
}
}
}
}
Here is the range query:
GET reseller_api_logging/_search
{
"query": {
"range" : {
"CreatedAt" : {
"gte" : "2017-01-01 01:01:49",
"lte" : "2017-01-30 09:01:49"
}
}
}
}
Here is a piece of one of the documents return on a match all search:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 50,
"max_score": 1,
"hits": [
{
"_index": "reseller_api_logging",
"_type": "logging",
"_id": "2142183",
"_score": 1,
"_source": {
"PastelAccountNumber": "103206",
"CreatedAt": "2017-01-23 09:01:49",
"HTTPmethod": "GET",
"Endpoint": "getServiceSessionDetailsById",
"RequestParams": "

Number format Exception For string type

I have a mapping like this
{
"settings": {
"analysis": {
"filter": {
"nGramFilter": {
"type": "nGram",
"min_gram": 3,
"max_gram": 20,
"token_chars": [
"letter",
"digit",
"punctuation",
"symbol"
]
},
"email" : {
"type" : "pattern_capture",
"preserve_original" : 1,
"patterns" : [
"([^#]+)",
"(\\p{L}+)",
"(\\d+)",
"#(.+)"
]
},
"number" : {
"type" : "pattern_capture",
"preserve_original" : 1,
"patterns" : [
"([^+-]+)",
"(\\d+)"
]
},
"edgeNGramFilter": {
"type": "nGram",
"min_gram": 1,
"max_gram": 10,
"token_chars": [
"letter",
"digit",
"punctuation",
"symbol"
]
}
},
"analyzer": {
"nGramAnalyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": [
"lowercase",
"nGramFilter"
]
},
"whitespaceAnalyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": [
"lowercase"
]
},
"email" : {
"tokenizer" : "uax_url_email",
"filter" : [
"email",
"lowercase",
"unique"
]
},
"number" : {
"tokenizer" : "whitespace",
"filter" : [ "number", "unique" ]
},
"edgeNGramAnalyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": [
"lowercase",
"edgeNGramFilter"
]
}
}
}
},
"users": {
"mappings": {
"user_profiles": {
"properties": {
"firstName": {
"type": "string",
"analyzer": "nGramAnalyzer",
"search_analyzer": "whitespaceAnalyzer"
},
"lastName": {
"type": "string",
"analyzer": "nGramAnalyzer",
"search_analyzer": "whitespaceAnalyzer"
},
"email": {
"type": "string",
"analyzer": "email",
"search_analyzer": "whitespaceAnalyzer"
},
"score" : {
"type": "string"
},
"homeLandline": {
"type": "string",
"analyzer": "number",
"search_analyzer": "whitespaceAnalyzer"
},
"dob": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"mobile": {
"type": "integer"
},
"residenceCity": {
"type": "string",
"analyzer": "edgeNGramAnalyzer",
"search_analyzer": "whitespaceAnalyzer"
},
"created_at": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
}
}
}
}
}
I can get the score as integer as well as "NA" so I mapped the type as string but while posting data to the index i am getting Number Format Exception.
For Example:
if I post first data as integer and followed by "NA". I am getting these exception.
while checking my log file I am getting this errors:
[2016-08-29 15:19:01] elasticlog.WARNING: Response ["{\"error\":{\"root_cause\":[{\"type\":\"mapper_parsing_exception\",\"reason\":\"failed
to parse
[score]\"}],\"type\":\"mapper_parsing_exception\",\"reason\":\"failed
to parse
[score]\",\"caused_by\":{\"type\":\"number_format_exception\",\"reason\":\"For
input string: \"NH\"\"}},\"status\":400}"] []
Your mapping is incorrect. It should be, assuming, users is the index name and user_profiles is the type:
{
"users": {
"mappings": {
"user_profiles": {
"properties": {
"score": {
"type": "string"
}
}
}
}
}
}
You have a missing mappings before user_profiles.

Categories