JSON-从PHP中的值获取平均值

时间:2019-04-08 19:33:31

标签: php json

我进行了搜索,但没有成功。我总是会遇到一些错误... 我想要的是获取按日期分组的“导入”值的平均值。

我很高兴有人能帮助我...

我的JSON文件:

[
  {
    "Date": "2019-03",
    "Import": "200",
    "Export": "50"
  },
  {
    "Date": "2019-03",
    "Import": "800",
    "Export": "200"
  },
  {
    "Date": "2019-04",
    "Import": "100",
    "Export": "600"
  }
]

我的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 $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>';

先谢谢了。 干杯

2 个答案:

答案 0 :(得分:2)

  

我想要的是获取“导入”值的平均值

简单

$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));

输出

367

Sandbox

这是所有行的汇总值,因此将其存储在每一行中没有多大意义。

如果不是所有行都具有Import,则可以将列设为变量并对其进行计数:

$import = array_column($array_origin, 'Import'); //["200","800","100"]
echo round(array_sum($import)/count($import));

更新 虽然还不清楚

  

否,因为如您所见,有一个“按日期”过滤器。您正在打印所有项目,而不是按日期。 :( – –

这仍然是一个微不足道的问题(一旦您知道有多少项和总数)。

$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);

输出

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
    )
 )

此外,此foreach循环中到处都是问题,所以我将其修复。主要是小事...

例如:

 isset($v['Date']) ? $stack[$v['Date']]['Import'] + $v['Import']

对于此值['Import'],这不会阻止添加读取错误。 isset($v['Date'])可能整天都是真实的,这告诉我们$stack[$v['Date']]['Import']是否已设置的任何信息。如果未设置它,而我们尝试读取它以进行加法(必须知道要添加的值),我们将收到未定义索引的通知。

Sandbox

现在如果您不想跟踪这些项目计数(出于任何原因)

这是一个很好的技巧(加上乐趣),可以获取给定日期的项目数:

  $num_dates = array_count_values(array_column($array_origin, 'Date'));

输出

Array
(
    [2019-03] => 2
    [2019-04] => 1
)

这将为您提供该信息,然后在回调中使用$num_dates(字面意思是双关语),并在项目的key中使用

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;
});

输出

Array
(
    [2019-03] => Array
        (
            [Import] => 1000
            [Export] => 250
            [Average_Import] => 125
        )

    [2019-04] => Array
        (
            [Import] => 100
            [Export] => 600
            [Average_Import] => 600
        )

)

Sandbox

答案 1 :(得分:0)

cpack
$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);