1

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

1 Answer 1

2

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'];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Prefect. Thanks :)
Sorry, allow me ask you, if I want make a average of the "Import"?
array_column($stack, 'Import') then array_sum / count
Thanks for you help, I appreciate so much :)

Your Answer

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.