0

I have a JSON file where I'm struggling getting the data out. Here is the JSON.

{"data":[
 {"tag":"operatingrevenue","value":215639000000.0},
 {"tag":"totalrevenue","value":215639000000.0},
 {"tag":"operatingcostofrevenue","value":131376000000.0},
 {"tag":"totalcostofrevenue","value":131376000000.0},
 {"tag":"totalgrossprofit","value":84263000000.0},
 {"tag":"sgaexpense","value":14194000000.0},
 {"tag":"rdexpense","value":10045000000.0},
 {"tag":"totaloperatingexpenses","value":24239000000.0},
 {"tag":"totaloperatingincome","value":60024000000.0},
 {"tag":"otherincome","value":1348000000.0},
 {"tag":"totalotherincome","value":1348000000.0},
 {"tag":"totalpretaxincome","value":61372000000.0},
 {"tag":"incometaxexpense","value":15685000000.0},
 {"tag":"netincomecontinuing","value":45687000000.0},
 {"tag":"netincome","value":45687000000.0},
 {"tag":"netincometocommon","value":45687000000.0},
 {"tag":"weightedavebasicsharesos","value":5470820000.0},
 {"tag":"basiceps","value":8.35},
 {"tag":"weightedavedilutedsharesos","value":5500281000.0},
 {"tag":"dilutedeps","value":8.31},
 {"tag":"weightedavebasicdilutedsharesos","value":5471500000.0},
 {"tag":"basicdilutedeps","value":8.35},
 {"tag":"cashdividendspershare","value":2.18}]

I'm converting it to an array using

$data = json_decode($jsondata, true);

I can then pull the data by:

$operatingRevenue = $data['data'][0]['value'];
$totalrevenue = $data['data'][1]['value'];

etc, however, I want to use the tag name and not just the order just in case the order changes in the JSON. Something like

$operatingRevenue = $data['data']['operatingRevenue'];
asked Jun 8, 2017 at 0:06
1
  • As an aside, that is some annoyingly-constructed JSON. Do you have the ability to modify the structure of the data sent instead? Commented Jun 8, 2017 at 0:55

2 Answers 2

1

Iterate the $data array, and set the key of a new element in the array to the tag element, and it's value to the value element.

foreach($data['data'] as $v)
 $array[$v['tag']] = $v['value'];

$array contains what you want, access like this: $array['operatingRevenue']

answered Jun 8, 2017 at 0:11
Sign up to request clarification or add additional context in comments.

Comments

0

Iterate $data and use array_push. Read it here. https://www.w3schools.com/php/func_array_push.asp

$data = json_decode($jsondata, true);
$datas = [];
foreach($data['data'] as $val){
 array_push($datas,["tag"=>$val['tag'],"value"=>$val['tag']])
}
answered Jun 8, 2017 at 0:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.