Hey saurav, try this out 😎
You can go to https://laravelplayground.com/ and paste this code to see it in action
<?php
/**
*
* method to convert api data to a better array format
* Following is the sample code of transformed data
[
date1 => [
productName1 => qty,
productName2 => qty,
productName3 => qty
],
date2 => [...],
...
]
*
*/
function transformedData(array $data)
{
$transoformedData = [];
$columns = $data[0];
foreach(array_slice($data,1) as $row)
{
$temp = [];
foreach(array_slice($columns,1) as $i => $productName)
{
$temp[$productName] = $row[$i+1];
}
$transoformedData[$row[0]] = $temp;
}
return $transoformedData;
}
/**
*
* method to combine two arrays by summing the values with common keys, if exist
*
*/
function sumArrays(array $a1, array $a2)
{
$a3 = $a1;
foreach($a2 as $k => $v) {
if(array_key_exists($k, $a3)) {
$a3[$k] += $v;
} else {
$a3[$k] = $v;
}
}
return $a3;
}
/**
*
* method to combine data came from two apis
*
*/
function combineAPIData($data1,$data2)
{
//transform data
$data1 = transformedData($data1);
$data2 = transformedData($data2);
$sumData = $data1;
foreach($data2 as $date => $sales)
{
$sumData[$date] = (array_key_exists($date,$sumData))
? sumArrays($sumData[$date], $sales)
: $sales;
}
return $sumData;
}
/****** TRY IT OUT *******/
// sample data from 1st api
$data1 = [
["Month","Apple","Orange","Guava","Banana"],
["Nov-16", 9 , 11 , 6, 10],
["Nov-18 " , 5 , 0 , 0, 4],
["Nov-13 " , 8 , 2 , 10, 2]
];
// sample data from 2nd api
$data2 = [
["Month", "Apple", "Banana", "Guava"],
["Nov-16" , 4 , 7 , 0],
["Nov-13 " , 12 , 8 , 9],
["Nov-15 " , 12 , 8 , 19]
];
dd(combineAPIData($data1, $data2));
/* sample output
array:4 [
"Nov-16" => array:4 [
"Apple" => 13
"Orange" => 11
"Guava" => 6
"Banana" => 17
]
"Nov-18 " => array:4 [
"Apple" => 5
"Orange" => 0
"Guava" => 0
"Banana" => 4
]
"Nov-13 " => array:4 [
"Apple" => 20
"Orange" => 2
"Guava" => 19
"Banana" => 10
]
"Nov-15 " => array:3 [
"Apple" => 12
"Banana" => 8
"Guava" => 19
]
]
**/