Chartjs-How can I divide values from two different arrays which are not of the same length?

0👍

Since you didn’t mention the full response from https://some-endpoint-for-once-in-3-months-dividend and https://some-endpoint-for-daily-prices. Im assuming a date key exists with the responses for example

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

For fetching the API responses

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

For calculating the DividendYield

public function DividendYield(){
   $dividend   = $this->fetchApiData('https://some-endpoint-for-once-in-3-months-dividend','date','dividend');

   $dailyPrice = $this->fetchApiData('https://some-endpoint-for-daily-prices','date','price');

   if(!empty($dividend)){
       $dividendColl  = collect($dividend);
       return collect($dailyPrice)->whereIn('date',$dividendColl->pluck('date'))
                                         ->map(fn($price)=>$dividendColl->where('date',$price['date'])
                                                                        ->map(fn($dividend)=> ['date'=>$price['date'],
                                                                                               'DividendYield'=>(($dividend['dividend']/$price['price'])*100)]))->collapse();     
   }}

0👍

So first you need to group your $price by month, assuming that the dd() in your comment is what priceis, by using:

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

then you need to loop through the $dividend:

$result = array();
foreach ($dividend as $key => $value) {
    $mounthResult = array();
    foreach ($price[key] as $p) {
// assuming dividend is the price you mean
        array_push($mounthResult, $value/$p->dividend*100);
    }
    array_push($result, $temp);
}

The $price[key] means the month group we want, so if key = 0 that means we are looping the first month.

I hope i get you right, feel free to comment on this to help me understand you more if i’m wrong.

Leave a comment