JSON - Sum values by date using php - php

I'm creating a simple script in php and json, however I have some difficulties to make Sums of multi values by date.
I want Sum "Import" and "Export" from each month.
This is what I want to print:
array (
'Date' => '2019-03',
'Import' => 1000,
'Export' => 250,
)
array (
'Date' => '2019-04',
'Import' => 100,
'Export' => 600,
)
My json:
[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]
This is my script php:
$url = dirname(__DIR__ ) . '/admin/json/all.json';
$json = file_get_contents($url);
$array_origin = json_decode($json, TRUE);
$stack=array();
foreach ($array_origin as $index => $array_part) {
$stack[$array_part['Date']] =array_key_exists($array_part['Date'],$stack)?$stack[$array_part['Date']]+$array_part['Import']:$array_part['Import'];
}
echo '<pre>' . var_export($stack, true) . '</pre>';
However with this script Im only able to Sum 'Import', but I want also Sum 'export'.
For that reason Im looking for your help.
I appreciate for any help from you guys.
Thanks in advance.
Cheers

You need to add Import and Export keys to the result array. I've attempted to shorten it and used isset:
foreach ($array_origin as $v) {
$stack[$v['Date']]['Import'] = isset($v['Date']) ? $stack[$v['Date']]['Import'] + $v['Import'] : $v['Import'];
$stack[$v['Date']]['Export'] = isset($v['Date']) ? $stack[$v['Date']]['Export'] + $v['Export'] : $v['Export'];
}

Related

JSON - Get average from values in php

I made a search but no success. I always get some error...
What I want is, get the average of the values "Import" grouped by date.
I appreciate if someone can help me...
My JSON file:
[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]
My PHP Script:
$url = dirname(__DIR__ ) . '/admin/json/all.json';
$json = file_get_contents($url);
$array_origin = json_decode($json, TRUE);
$stack=array();
foreach ($array_origin as $v) {
$stack[$v['Date']]['Import'] = isset($v['Date']) ? $stack[$v['Date']]['Import'] + $v['Import'] : $v['Import'];
$stack[$v['Date']]['Export'] = isset($v['Date']) ? $stack[$v['Date']]['Export'] + $v['Export'] : $v['Export'];
$stack[$v['Date']]['Average_Import'] = 'GET HERE AVERAGE';
}
echo '<pre>' . var_export($stack, true) . '</pre>';
Thanks in advance.
Cheers
What I want is, get the average of the values "Import"
Simple
$array_origin = json_decode('[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]', true);
echo round(array_sum(array_column($array_origin, 'Import'))/count($array_origin));
Output
367
Sandbox
This is an aggregate value of all the rows, so it doesn't make much sense to store it in each of the rows.
If not all rows have the Import you can just make the column a variable and count that instead:
$import = array_column($array_origin, 'Import'); //["200","800","100"]
echo round(array_sum($import)/count($import));
UPDATE
While this wasn't clear
No, because as you see, have a filter "by date". You are printing all itens, not by date. :( –
It's still a trivial problem (once you know how many items there are and the total).
$stack = [];
foreach ($array_origin as $v) {
$key = $v['Date'];
if(!isset($stack[$key])) $stack[$key] = [];
$stack[$key]['Import'] = isset($stack[$key]['Import']) ? $stack[$key]['Import'] + $v['Import'] : $v['Import'];
$stack[$key]['Export'] = isset($stack[$key]['Export']) ? $stack[$key]['Export'] + $v['Export'] : $v['Export'];
//track the number of items
$stack[$key]['items'] = isset($stack[$key]['items'] ) ? ++$stack[$key]['items'] : 1;
$stack[$key]['Average_Import'] = 'GET HERE AVERAGE';
}
//cant average tell you know what they are, this will have to be done after the foreach
array_walk($stack,function(&$item){
$item['Average_Import'] = $item['Export']/$item['items'];
return $item;
});
print_r ($stack);
Output
Array
(
[2019-03] => Array
(
[Import] => 1000
[Export] => 250
[items] => 2
[Average_Import] => 125
)
[2019-04] => Array
(
[Import] => 100
[Export] => 600
[items] => 1
[Average_Import] => 600
)
)
Additionally, this foreach loop was just littered with issues, so I fixed them up. Mostly little things...
For example:
isset($v['Date']) ? $stack[$v['Date']]['Import'] + $v['Import']
This does nothing to prevent read errors from addition, for this value ['Import']. This isset($v['Date']) can be true all day long and that tells us nothing about if $stack[$v['Date']]['Import'] is set or not. If it's not set and we try to read it for addition (have to know its value to add to it) we will get a notice for undefined index.
Sandbox
Now If you don't want to track those item counts ( for whatever reason )
This is a nice trick (plus its fun) to get the number of items for a given date:
$num_dates = array_count_values(array_column($array_origin, 'Date'));
Output
Array
(
[2019-03] => 2
[2019-04] => 1
)
That will give you that information, Then use $num_dates in the callback (literally, pun intended) and the key of the item:
foreach ($array_origin as $v) {
$key = $v['Date'];
if(!isset($stack[$key])) $stack[$key] = [];
$stack[$key]['Import'] = isset($stack[$key]['Import']) ? $stack[$key]['Import'] + $v['Import'] : $v['Import'];
$stack[$key]['Export'] = isset($stack[$key]['Export']) ? $stack[$key]['Export'] + $v['Export'] : $v['Export'];
$stack[$key]['Average_Import'] = 'GET HERE AVERAGE';
}
$num_dates = array_count_values(array_column($array_origin, 'Date'));
array_walk($stack,function(&$item,$key)use($num_dates){
//may want to check if $key exists (but it should always)
$item['Average_Import'] = $item['Export']/$num_dates[$key];
return $item;
});
Output
Array
(
[2019-03] => Array
(
[Import] => 1000
[Export] => 250
[Average_Import] => 125
)
[2019-04] => Array
(
[Import] => 100
[Export] => 600
[Average_Import] => 600
)
)
Sandbox
$array_origin = json_decode('[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]', true);
$counts = [];
$imports = [];
foreach ($array_origin as $data) {
if (isset($data['Import']) && isset($data['Date'])) {
if (!isset($counts[$data['Date']])) {
$counts[$data['Date']] = 0;
$imports[$data['Date']] = 0;
}
$counts[$data['Date']]++;
$imports[$data['Date']] = intval($data['Import']) + $imports[$data['Date']];
}
}
$importAverage = [];
foreach ($imports as $date => $importSum) {
$importAverage[$date] = $importSum > 0 ? $importSum / $counts[$date] : 0;
}
var_dump($importAverage);
array (size=2)
'2019-03' => int 500
'2019-04' => int 100

create embedded json for autocomplete

I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)

convert php response array as comma separated [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am trying to get facebook friends by using facebook api.
I am getting response
{
"data": [
{
"id": "groupID",
"members": {
"data": [
{
"name": "Abc",
"administrator": false,
"id": "xxxxxx"
},
{
"name": "NewCas",
"administrator": false,
"id": "xxxxxxxxx"
},
{
"name": "Cds",
"administrator": false,
"id": "xxxxxxxxx"
},
{
"name": "akaha",
"administrator": false,
"id": "xxxxxxx"
},
}
}
This is my code
$fql = 'https://graph.facebook.com/me/groups?fields=id,members&access_token='.$access_token.'&limit=3';
$fqlresult = file_get_contents($fql);
$f = json_decode($fqlresult, true);
tried implode.
$result = implode(',', array_column($f['data'], 'id'));
I am getting this response
GroupID,GroupID,GroupID
I want to take response user ids (members id) as
xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx
Thanks
The other answers are almost correct, but the data is an array with one element so it should be:
echo implode(',', array_column($f['data'][0]['members']['data'], 'id'));
and that is when you have only one groupid, if you have multiple group ids you will need to loop trough it. (loop over the [0] by checking $groupcount = count($f['data']);
This works...
$arr = array(
'data' => array(
array('id' => 'xxxx1'),
array('id' => 'xxxx2'),
array('id' => 'xxxx3'),
array('id' => 'xxxx4'),
array('id' => 'xxxx5'),
array('id' => 'xxxx6'),
array('id' => 'xxxx7'),
array('id' => 'xxxx8'),
)
);
echo implode(',', array_column($arr['data'], 'id'));
EDIT - based on your update and change of request...
echo implode(',', array_column($arr['data'][0]['members']['data'], 'id'));
please review http://php.net/manual/en/language.types.array.php and the section on multidimensional arrays
$data_arr=json_decode($data,true);
$return_str="";
foreach($data_arr['data'] as $row)
{
$return_str .=implode(", ", array_column($row['members']['data'], 'id')) ;
}
echo rtrim($return_str,",");
This will work for multiple elements in $f['data'].
echo implode(',', array_column($f['data'][0]['members']['data'], 'id'));
Make sure your PHP version is 5.5+. Below the specified version will not support array_column function. You can also use this code without array_column.
$data = $result['data'][0]['members']['data'];
$keyValue = '';
foreach ($data as $outerKey => $outerValue) {
foreach ($outerValue as $key => $value) {
if($key == 'id'){
$keyValue .= $value . ' ';
}
}
}
echo $keyValue;

how to get a value of multidimensional array on php

hi im bulding a site with php that use a json api and i need to echo the values of an multidimensional array
"troopsLevels": [
{
"value": 5,
"globalID": 4000000
},
{
"value": 5,
"globalID": 4000001
},
{
"value": 4,
"globalID": 4000002
},
this is a example of my json file what i need is to show the value "value" knowing depending of the globalID
but not sure how to do it
i was thinking something like
$troop_lvl = $data['troopsLevels'];
if($troop_lvl['globalID'] == 4000000){echo $troop_lvl['value']}
but of curse this will not work as i dont specify the item [0]..[2]
but that actually thats what i need to avoid using [0] to select specific array i need to read all and only show the ['value'] when i give the globalid
i really hope yo can understand me english is not my mother language
thanks a lot for you help
You need to use foreach loop
foreach ($troop_lvl as $key=>$value) {
if($value['globalID'] == 4000000) {
echo $value['value'];
}
}
Use foreach
foreach ($troop_lvl as $key=>$value) {
if($value['globalID'] == 4000000) {
echo $troop_lvl['value'];
}
}
See below:
<?php
$arr = array("test" => array("value" => 1, "value2" => 2), "test2" => array("value" => 21, "value2" => 22));
$encode_arr = json_encode($arr);
$decode_arr = json_decode($encode_arr);
//print_r($decode_arr);
foreach ($decode_arr as $key => $value) {
if($value->value2==2)
echo $value->value;
}
?>
The output will be 1.
This should work for you,
$a = '{"troopsLevels": [
{
"value": 5,
"globalID": 4000000
},
{
"value": 5,
"globalID": 4000001
},
{
"value": 4,
"globalID": 4000002
}
]}';
$abc = json_decode($a);
foreach ($abc->troopsLevels as $row) {
if ($row->globalID == 4000000) {
echo $row->value;// prints value as 5 for the current input.
}
}

Convert PHP array to JSON using multi dimentional arrays

I am trying to convert this php array to a json. This is my code:
$c = array();
$c = array(
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
),
);
$json = json_encode($c);
echo $json;
This is the output I'd like to acieve:
{"cronjobs":[{"id":1186437,"groupId":12379]}
Though using the above code this is what I am getting
[{"id":1189515,"groupId":12379}]
The [{"cronjobs"part is not appearing.
I'm not sure what I'm doing wrong.
This should get the result that you want (just wrap an array around the id, groupId array):
<?php
$c = array();
$c['cronjobs'] = array(array(
'id'=>1189515,
'groupId'=>12379,
));
echo json_encode($c);
// result {"cronjobs":[{"id":1189515,"groupId":12379}]}
?>
This is how you need to format your array:
$c = array(); // declare the array
$c['cronjobs'] = array( // populate the array
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c); // json_encode it
echo $json;
There is no need for $c = array($c['cronjob']); (which was what you were doing).
I think this is what you're looking for:
$c = array('cronjobs' => array());
$c['cronjobs'][] = array('id' => 1189515, 'groupId' => 12379);
//$c['cronjobs'][] = array('id' => 1234, 'groupId' => 4321);
$json = json_encode($c);
echo $json;
Cronjobs needs to contain an array of cronjob objects/arrays
Could also be written using one statement, like this:
$c = array('cronjobs' => array(
array('id' => 1189515, 'groupId' => 12379),
array('id' => 1234, 'groupId' => 4321)
));
Your problem is that in PHP array is used to represent both JSON objects and JSON lists hence the confusion. Consider the following code:
$cronjob = array(
'id' => 1189515,
'groupId' => 12379
);
echo json_encode($cronjob);
// {"id":1189515,"groupID":12379"}
As you can see this represents a single object. So we'll create a list of objects:
$cronjobs = array($cronjob);
echo json_encode($cronjobs);
// [{"id":1189515,"groupID":12379"}]
This is now a list as expected. Now the parent object:
$c = array(
'cronjobs' => $cronjobs
);
echo json_encode($c);
// {"cronjobs":[{"id":1189515,"groupID":12379"}]}
In JSON there is a name: value pair system
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
if you want to achieve like {"cronjobs":[{"id":1186437,"groupId":12379]} then the array must be named like the following in PHP:
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c);
echo $json;

Categories