ChartJS 如何将两个长度不同的数组中的值相除?

5anewei6  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(207)

我试图在laravel项目中使用ChartJs从一家公司获取过去20年的DividendYield。数组来自HTTP客户端API。公式如下:$dividendPayed / $dailyPrice * 100。我面临的问题是,$dividendPayed是三个月一次,因此它使数组比包含每日价格的数组短。

  1. private function getDividend()
  2. {
  3. $dividend = [];
  4. $response = Http::get('https://some-endpoint-for-once-in-3-months-dividend');
  5. $response->throw();
  6. foreach($response->json('historical') as $stock){
  7. $dividend [] = $stock['dividend'];
  8. }
  9. return $dividend;
  10. //THIS ARRAY RETURNS LET'S SAY FOR EXAMPLE 50 RESULTS
  11. // $dividend = [
  12. 0 => 0.23
  13. 1 => 0.23
  14. 2 => 0.22
  15. 3 => 0.22
  16. ..........
  17. 50 => .43
  18. ]
  19. }
  20. private function getPrice()
  21. {
  22. $price = [];
  23. $response = Http::get('https://some-endpoint-for-daily-prices');
  24. $response->throw();
  25. foreach($response->json('historical') as $stockPrice){
  26. $price [] = $stockPrice['close'];
  27. }
  28. return $price;
  29. }
  30. //THIS ARRAY RETURNS LET'S SAY FOR EXAMPLE 240 RESULTS
  31. // $price = [
  32. 0 => 147.27
  33. 1 => 143.39
  34. 2 => 143.86
  35. 3 => 143.75
  36. 4 => 142.41
  37. 5 => 138.38
  38. ..........
  39. 240 => 300.43
  40. ]

我还必须提到,图表中标签的“日期”(过去20年的逐日)是从与$dailyPrice相同的端点获取的。

szqfcxe2

szqfcxe21#

由于您没有提到来自https://some-endpoint-for-once-in-3-months-dividend和https://some-endpoint-for-daily-prices的完整响应,我假设响应中存在一个日期键,例如

  1. ['historical'=>[['date'=>'2022-03-03','price'=>0.2]];

用于获取API响应

  1. private function fetchApiData(string $api,string $dateKey,string $priceKey,string $mainRespKey='historical'){
  2. $data = [];
  3. $response = Http::get($api);
  4. $response->throw();
  5. return $response->json($mainRespKey);}

用于计算股息收益率

  1. public function DividendYield(){
  2. $dividend = $this->fetchApiData('https://some-endpoint-for-once-in-3-months-dividend','date','dividend');
  3. $dailyPrice = $this->fetchApiData('https://some-endpoint-for-daily-prices','date','price');
  4. if(!empty($dividend)){
  5. $dividendColl = collect($dividend);
  6. return collect($dailyPrice)->whereIn('date',$dividendColl->pluck('date'))
  7. ->map(fn($price)=>$dividendColl->where('date',$price['date'])
  8. ->map(fn($dividend)=> ['date'=>$price['date'],
  9. 'DividendYield'=>(($dividend['dividend']/$price['price'])*100)]))->collapse();
  10. }}
展开查看全部
oo7oh9g9

oo7oh9g92#

因此,首先您需要按月份对您的$price进行分组,假设您的评论中的dd()就是price,方法是:

  1. $price = collect($price)->groupBy(function($val) {
  2. return Carbon::parse($val->date)->format('m');
  3. });

则需要循环$dividend

  1. $result = array();
  2. foreach ($dividend as $key => $value) {
  3. $mounthResult = array();
  4. foreach ($price[key] as $p) {
  5. // assuming dividend is the price you mean
  6. array_push($mounthResult, $value/$p->dividend*100);
  7. }
  8. array_push($result, $temp);
  9. }

$price[key]表示我们想要的月份组,因此如果key = 0,则意味着我们正在循环第一个月份。
我希望我得到你的权利,随时评论这一点,以帮助我了解你更多,如果我错了。

展开查看全部

相关问题