I need to sum values of json object using PHP
json
{
"links": [
{
"source": 9887878787,
"target": 9999999993,
"value": 1
},
{
"source": 9999999993,
"target": 9887878787,
"value": 2
}
]
}
Want to Combine value of first and second object to get
desired output
{
"links": [
{
"source": 9887878787,
"target": 9999999993,
"value": 3
},
{
"source": 9999999993,
"target": 9887878787,
"value": 3
}
]
}
How can I achieve this without using javasript.I need php script for that?
Thank you a lot in advance.
Here is a way to do it :
$data = json_decode('{
"links": [
{
"source": 9887878787,
"target": 9999999993,
"value": 1
},
{
"source": 9999999993,
"target": 9887878787,
"value": 2
}
]
}');
$sum = 0;
foreach ($data->links as $link) {
$sum += $link->value;
}
foreach ($data->links as &$link) {
$link->value = $sum;
}
echo json_encode($data);
Hope this helps.
Related
I am getting an array from an API that varies in number of levels but follows the same basic structure - here is a truncated sample as this particular repsonse is 25K lines:
{
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Ordinary Income/Expenses"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Rows": {},
"Summary": {
"ColData": [
{
"value": "Gross Profit"
},
{
"value": ""
}
]
},
"type": "Section"
},
{
"Header": {
"ColData": [
{
"value": "Income"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "40000 Sales Income",
"id": "31"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Rows": {
"Row": [
{
"ColData": [
{
"value": "2022-01-24"
},
{
"value": "Invoice",
"id": "148774"
},
{
"value": "208232"
},
{
"value": "Hyatt:#211102",
"id": "7568"
},
{
"value": "JN",
"id": "4100000000000368107"
},
{
"value": "CAPTIVE AIRE"
},
{
"value": "11000 Accounts Receivable",
"id": "80"
},
{
"value": "38748.00"
},
{
"value": "38748.00"
}
],
"type": "Data"
},
I need to traverse the json, and where there is data in both [Header][ColData][value] AND [Header][ColData][id] extract the value, id (in this snippet "value": "40000 Sales Income", "id": "31") and the data that immediately follows the "value"/"id" in [Rows][Row][Rows][Row][ColData] (in this snippet starting with "ColData": [{"value": "2022-01-24"...)
[Rows][Row][Rows][Row][ColData] will have one to a few hundred subarrays. I can extract the data from the subarrays once they are found - it's just managing the varying depths of the array that is warping my brain.
[Rows][Row][Rows][Summary] can be discarded as well.
I have tried multiple foreach loops - but by time I get 5 or 6 levels deep it gets very confusing. The number of Header sections varies depending on the report type. The [Rows][Row] nesting is multiple layers deep... I'm sure there has to be a better way than nesting foreach loops...
This is what I've come up with. Kindly modify it to meet your need.
$array = json_decode($json, true);
function traverse_some_array($array){
$result = [];
foreach($array['Rows']['Row'] ?? [] as $row){
if( !empty($row['Header']['ColData']) ){
foreach($row['Header']['ColData'] as $coldata){
if( isset($coldata['value'], $coldata['id']) ){
// there is data in both [Header][ColData][value] AND [Header][ColData][id]
// extract the value, id (in this snippet "value": "40000 Sales Income", "id": "31")
$extract_data = [
'value' => $coldata['value'],
'id' => $coldata['id']
];
// the data that immediately follows the "value"/"id" in [Rows][Row][Rows][Row][ColData]
$immediate_coldata = $row['Rows']['Row'] ?? [];
// you can do what ever you want with the results, eg return it or push it to a result array
$result[] = [
'extract_data' => $extract_data,
'immediate_coldata' => $immediate_coldata
];
}else{
// continue traversing the array
$result = array_merge($result, traverse_some_array($row));
}
}
}
}
return $result;
}
print_r(traverse_some_array($array));
I am new to PHP programming and I need your lights!
I have a JSON file like:
"data": [{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
}]
and I have to change it using another json file which is like:
"diagnostics_keys": [
{
"ID": 1,
"type": "BTTPV",
"key": "0_193_bttpv",
"unit": "V"
},
{
"ID": 2,
"type": "BTTPC",
"key": "0_195_bttpc",
"unit": "A"
},
{
"ID": 3,
"type": "AVGKMKWH",
"key": "0_202_avgkmKwh",
"unit": "Km/Kwh"
}]
How can I combine these two (using the ID and type keys/values of the second json and replace the DIAGNOSTIC_TYPE_ID with those on first json)and take a result like the bellow json?
"data": [{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
}]
Would anyone have any points or links that may know and may help?
//change to arrays
$data = json_decode(YOUR_DATA_JSON, true); // I don't know your json variable names, so replace them
$diagnosticKeys = json_decode(YOUR_DIAGNOSTIC_KEYS_JSON, true);
//iterate over data, this is the one you want to change
foreach ($data as &$dataItem) {//(& is for replacing the values)
//another foreach for diagnostic keys
foreach ($diagnosticKeys as $diagnosticKey) {
if ($dataItem["DIAGNOSTIC_TYPE_ID"] == $diagnosticKey["ID"] {
$dataItem["DIAGNOSTIC_TYPE_ID"] = $diagnosticKey["type"];
}
}
}
//change to json again
$data = json_encode($data);
Not tested but should work.
$data1 = json_decode($json1);
$data2 = json_decode($json2);
$result = [];
foreach ($data1->data as $key => $value) {
foreach($data2->diagnostics_keys as $i => $val){
if($value->DIAGNOSTIC_TYPE_ID==$val->ID){
$value->DIAGNOSTIC_TYPE_ID = $val->type;
$result[$key]['DIAGNOSTIC_TYPE_ID'] = $val->type;
$result[$key]['VALUE'] = $value->VALUE;
}
}
}
echo json_encode($result);
So, I am receiving json input. I don't know how many inputs I will receive. I know how to turn this into an array, however I need to mix up how the array is structured. Array is currently multidimensional and associative already however is using the wrong associations. For me, it's using 'label' and 'value but I need these two to be in one associative array which use 'x' and 'y' so I can use them in a chart.
Example json
{
"metingen": [
{
"label": "06-06-2019 13:13:38",
"value": 25.21
},
{
"label": "06-06-2019 13:51:04",
"value": 27.69
},
{
"label": "06-06-2019 13:52:04",
"value": 27.69
},
{
"label": "06-06-2019 13:53:06",
"value": 27.61
},
{
"label": "06-06-2019 13:54:08",
"value": 27.56
},
{
"label": "06-06-2019 13:55:08",
"value": 27.55
},
{
"label": "06-06-2019 13:56:09",
"value": 27.55
},
{
"label": "06-06-2019 13:57:09",
"value": 27.53
},
{
"label": "06-06-2019 14:05:12",
"value": 28.51
},
{
"label": "06-06-2019 14:06:12",
"value": 28.53
},
{
"label": "06-06-2019 14:07:13",
"value": 28.51
},
{
"label": "06-06-2019 14:08:13",
"value": 28.51
},
{
"label": "06-06-2019 14:09:14",
"value": 28.53
},
{
"label": "06-06-2019 14:10:14",
"value": 28.52
},
{
"label": "06-06-2019 14:11:15",
"value": 28.52
},
{
"label": "06-06-2019 14:12:15",
"value": 28.54
},
{
"label": "06-06-2019 14:13:16",
"value": 28.53
},
{
"label": "06-06-2019 14:14:16",
"value": 28.48
},
{
"label": "06-06-2019 14:15:17",
"value": 28.39
},
{
"label": "06-06-2019 14:16:17",
"value": 28.37
}
],
"title": "Temperature for ICT Boven"
}
The PHP I'm using
$dataPoints = array();
foreach($charts as $key=> $chart)
{
$j=0;
$x=$chart[0]['label'];
$y=$chart[0]['value'];
$i=array($x,$y);
$dataPoints[0]=$i;
}
dataPoints array
(
array("x"=>"06-06-2019 13:13:38","y"=>25.21)//And then a lot of these arrays
)
You can use array_map with array_combine as follows,
$temp['metingen'] = array_map(function ($item) {
return array_combine(['x', 'y'], $item); // x and y are keys and label and value are values
}, $temp['metingen']);
Demo
you can use foreach with json_decode
$jToArr = json_decode($json, true);
$res = [];
foreach($jToArr['metingen'] as $key => $value){
$res[] = ['x' => $value['label'], 'y' => $value['value']];
}
print_r($res);
Working DEMO
i am tring to parse a special json content. I got this as an output file from a cucumber execution. The goal is it to decode some values like the name the status and some other content. How can i encode that.
Another concern would be a transformation of json into a CSV.
It is not important for me to use php. Java or Perl would be an alternative.
This file I am gonna call in php with:
$jsonconntent = file_get_contents("/home/xxx/test1.json");
The json conten looks like this (I posted only the beginning):
[
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
"type": "scenario",
"before": [
{
"output": [
"Default Timestamp start: 1516024716000"
],
"match": {
"location": "features/support/env.rb:32"
},
"result": {
"status": "passed",
"duration": 191690
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:13"
},
"result": {
"status": "passed",
"duration": 52117
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:21"
},
"result": {
"status": "passed",
"duration": 25885
}
}
],
"steps": [
{
"keyword": "Given ",
"name": "a Android A-Party",
"line": 4,
"output": [
"Got handset with number unvisable, IMSI: notfor, android-Id: yourfone, VNC: 11111, port: 9981"
],
"match": {
"location": "features/step_definitions/idrp_steps.rb:11"
},
"result": {
"status": "passed",
"duration": 1415024760
},
"after": [
{
"match": {
"location": "features/support/env.rb:24"
},
"result": {
"status": "passed",
"duration": 264339
}
}
]
}
Use:
$data = json_decode($jsonconntent, true);
You will have the data with javascript objects as arrays, not PHP objects.
To save it as CSV, it depends on the structure of the data. In this case, it is complicated:
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
...
How do you put the data in the column elements? Data is so nested that it cannot be transformed into a tabular format with column headers and one value per column in each row.
As to how to access the data, you can do this:
$first_element_id = $data[0]['elements'][0]['id'];
foreach ( $data as $item ) {
$uri = $item['uri'];
foreach ( $item['elements'] as $element ) {
$name = $element['name'];
}
}
As asked in one of the comments, this is how to access the 'Default Timestamp start':
foreach ($data as $item) {
foreach ($item['elements'] as $element) {
foreach ($element['before'] as $before) {
if (isset($before['output'])) {
foreach ($before['output'] as $output) {
echo sprintf("%s\n", $output);
}
}
}
}
}
Newbie here, I'm trying to get facebook name of user who left comment on my facebook page post but its not working. I'm using graph API v2.6. Here is my code:
$data = $this->check_file_get_contents($this->graph_api.$object_id.'/comments?
fields=from,name&access_token='.$access_token);
//$data = $this->check_file_get_contents($this->graph_api.$object_id.'/&access_token='.$access_token);
$res = json_decode($data);
$uname = $res->name;
echo $uname;
Any idea of what could be wrong here? Little guidance would be very helpful. What did I miss?
The $object_id is the Post ID. This is the output from graph api:
{
"data": [
{
"from": {
"name": "John Doe",
"id": "932242153456808"
},
"id": "585601208257495_620658141418468"
},
{
"from": {
"name": "Jason King",
"id": "10153078961444510"
},
"id": "585601208257495_622535501230732"
},
{
"from": {
"name": "Jason King",
"id": "10153078961444510"
},
"id": "585601208257495_622588581225424"
}
],
"paging": {
"cursors": {
"before": "WTI5dGJXVnVkRjlqZAFhKemIzSTZAOakl3TmpVNE1UUXhOREU0TkRZANE9qRTBOalEyTkRRMU5EZAz0ZD",
"after": "WTI5dGJXVnVkRjlqZAFhKemIzSTZAOakl5TlRnNE5UZA3hNakkxTkRJME9qRTBOalV3TnpVNE9Uaz0ZD"
}
}
}
Try this out
<?php
$json='{
"data": [
{
"from": {
"name": "John Doe",
"id": "932242153456808"
},
"id": "585601208257495_620658141418468"
},
{
"from": {
"name": "Jason King",
"id": "10153078961444510"
},
"id": "585601208257495_622535501230732"
},
{
"from": {
"name": "Jason King",
"id": "10153078961444510"
},
"id": "585601208257495_622588581225424"
}
],
"paging": {
"cursors": {
"before": "WTI5dGJXVnVkRjlqZAFhKemIzSTZAOakl3TmpVNE1UUXhOREU0TkRZANE9qRTBOalEyTkRRMU5EZAz0ZD",
"after": "WTI5dGJXVnVkRjlqZAFhKemIzSTZAOakl5TlRnNE5UZA3hNakkxTkRJME9qRTBOalV3TnpVNE9Uaz0ZD"
}
}
}';
$res=json_decode($json,true);
$data=$res['data'];
for ($x = 0; $x <= count($data)-1; $x++) {
echo $data[$x]['from']['name']."<br>\n";
}
?>
Output:
John Doe<br>
Jason King<br>
Jason King<br>