Loop trough and modify JSON response - php

I am making API request to Google Sheets and I receive this response:
Array
(
[0] => Array
(
[Title] => Hours
[January] => 1
[February] => 2
[March] => 3
[April] => 4
[May] => 5
[June] => 6
[July] => 7
[August] => 8
)
[1] => Array
(
[Title] => Days
[January] => 3
[February] => 5
[March] => 1
[April] => 6
[May] => 3
[June] => 7
[July] => 4
[August] => 2
)
[2] => Array
(
[Title] => Weeks
[January] => 3
[February] => 5
[March] => 3
[April] => 4
[May] => 0
[June] => 0
[July] => 2
[August] => 6
[September] => 0
[October] => 0
[November] => 1
[December] => 0
)
)
How could I loop trough and modify this array to something like this so I can use it with HighCharts JS library?
series: [{
title: 'Hours',
data: [1, 2, 3, 4, 5, 6 .......]
}, {
title: 'Days',
data: [4, 6, 3, 6, ........]
}, {
title: 'Weeks',
data: [1, 9, 1, 3, ........]
}, {
....
}]
I tried this way:
if ($response->status) {
$rawData = json_decode(json_encode($response->data), true);
}
$series = [];
foreach ($rawData as $index => $rawDatum) {
if (!isset($rawDatum['Title'])) {
continue;
}
foreach ($rawDatum as $columnKey => $value) {
if ($columnKey == 'CvA') {
$series[$columnKey]['Title'][] = $value;
}
}
}
What I got as result:
Array
(
[Title] => Array
(
[title] => Array
(
[0] => Hours
[1] => Days
[2] => Weeks
)
)
)
Also is there a way to get all names of the months saved in $months array for example without doubles?

The following piece of code will create an array with title and the values for each respective subarray Hours, Days, Weeks.
We will also collect the union of the months in an array named $months.
$series = [];
$months = [];
foreach ($rawData as $subarray) {
$title = $subarray['Title'];
// Remove title key
unset($subarray['Title']);
$series[] = [
'title' => $title,
'data' => array_values($subarray),
];
// Union operator to keep unique months.
$months += array_keys($subarray);
}
echo '<pre>';
print_r($months);
echo '</pre>';
echo '<pre>';
print_r($result);
echo '</pre>';
Result $months:
Array
(
[0] => January
[1] => February
[2] => March
[3] => April
[4] => May
[5] => June
[6] => July
[7] => August
[8] => September
[9] => October
[10] => November
[11] => December
)
Result $series:
Array
(
[0] => Array
(
[title] => Hours
[data] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
)
[1] => Array
(
[title] => Days
[data] => Array
(
[0] => 3
[1] => 5
[2] => 1
[3] => 6
[4] => 3
[5] => 7
[6] => 4
[7] => 2
)
)
[2] => Array
(
[title] => Weeks
[data] => Array
(
[0] => 3
[1] => 5
[2] => 3
[3] => 4
[4] => 0
[5] => 0
[6] => 2
[7] => 6
[8] => 0
[9] => 0
[10] => 1
[11] => 0
)
)
)

Given this data:
$data = [
[
'Title' => 'Hours',
'January' => 1,
'February' => 2,
'March' => 3,
'April' => 4,
'May' => 5,
'June' => 6,
'July' => 7,
'August' => 8,
],
[
'Title' => 'Days',
'January' => 3,
'February' => 5,
'March' => 1,
'April' => 6,
'May' => 3,
'June' => 7,
'July' => 4,
'August' => 2,
],
[
'Title' => 'Weeks',
'January' => 3,
'February' => 5,
'March' => 3,
'April' => 4,
'May' => 0,
'June' => 0,
'July' => 2,
'August' => 6,
'September' => 0,
'October' => 0,
'November' => 1,
'December' => 0,
]
];
You should be able to do this:
// Store everything here
$result = [];
foreach ($data as $item) {
// Grab the title
$ret['title'] = $item['Title'];
// Remove it from the source dataset
unset($item['Title']);
// Take the remaining values, join with comma
$ret['data'] = implode(',', array_values($item));
// Append to main array
$result[] = $ret;
}
You can skip the implode if want an actual array

Related

how to group array by given month and sum of total?

I want to get result as sum of total and group by month,
my array look like:
Array
(
[0] => Array
(
[order_no] => 222
[month] => Aug-22
[totalAmount] => 2305
)
[1] => Array
([order_no] => 333
[month] => Aug-22
[totalAmount] => 945
)
[2] => Array
(
[order_no] => 1
[month] => Sep-22
[totalAmount] => 945
)
[3] => Array
(
[order_no] => 111
[month] => Sep-22
[totalAmount] => 2305
)
)
What I am trying to do:
I want to group these data by MONTH and return the sum
Expected Result:
Array
(
[0] => Array
(
[month] => Aug-22
[totalAmount] => 3254
)
[1] => Array
(
[month] => Sep-22
[totalAmount] => 3254
)
)
This is classic problem to use array_reduce function:
<?php
$arr = [
["order_no" => 222, "month" => "Aug-22", "totalAmount" => 2305],
["order_no" => 333, "month" => "Aug-22", "totalAmount" => 945],
["order_no" => 1, "month" => "Sep-22", "totalAmount" => 945],
["order_no" => 111, "month" => "Sep-22", "totalAmount" => 2305],
];
$res = array_reduce(
$arr,
function($acc, $order) {
if (isset($acc[$order['month']])) {
$acc[$order['month']]['totalAmount'] += $order['totalAmount'];
} else {
$acc[$order['month']] = [
"month" => $order['month'], "totalAmount" => $order['totalAmount']
];
}
return $acc;
},
[]
);
print_r($res);
run php online

How can I combine 2 array in php or laravel

I would like to combine 2 arrays into 1 in PHP or laravel. I've searched this site for similar questions but can't seem to find an answer.
Can someone help me with this?
**array 1 -- $insertData **
Array
(
[0] => Array
(
[prid] => 4
[vendor_id] => 1
)
[1] => Array
(
[prid] => 5
[vendor_id] => 2
)
)
**Array - 2 $requestData **
Array
(
[vendor_id] => Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 2
)
[item] => Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)
[qty] => Array
(
[0] => 12
[1] => 13
[2] => 14
[3] => 15
)
)
**Required Output ---- how can I do this array1 and array2 combine into a single array **
Array
(
[0] => Array
(
[prid] => 4
[vendor_id] => 1
[item] => 2
[qty] => 12
)
[1] => Array
(
[prid] => 4
[vendor_id] => 1
[item] => 3
[qty] => 13
)
[2] => Array
(
[prid] => 5
[vendor_id] => 2
[item] => 4
[qty] => 14
)
[3] => Array
(
[prid] => 5
[vendor_id] => 2
[item] => 5
[qty] => 15
)
)
My controller
public function prtmulti(Request $req)
{
$maxPrId = newpr::max('prid');
// print_r($maxPrId);
echo "<pre>";
$requestData = $req->all();
if (array_key_exists("vendor_name", $requestData)) {
$insertData = [];
$uniqueData = array_unique($requestData["vendor_name"]);
foreach ($uniqueData as $key => $value) {
$maxId = $maxPrId+1;
$insertData[] = ['prid' => $maxId, 'vendor_id' => $value];
$maxPrId = $maxPrId+1;
}
}
print_r($insertData);
print_r($requestData);
}
you can achieve this using the array_combine function in php, for example:
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
I'm pretty sure that Laravel doesn't offer anything out of the box to execute your desired merging technique (and I don't see why it would bother).
Assuming that the vendor_id values in the first array are unique, you will get best performance by creating a lookup array. array_column() can be used to declare an array with vendor_id values as keys and prid values as values.
Because your $requestData has rows with the number of columns desired in the output, loop over the $requestData['vendor_id'] data and manually generate the desired rows of data in the result array.
Code: (Demo)
$insertData = [
['prid' => 4, 'vendor_id' => 1],
['prid' => 5, 'vendor_id' => 2],
];
$requestData = [
'vendor_id' => [1, 1, 2, 2],
'item' => [2, 3, 4, 5],
'qty' => [12, 13, 14, 15]
];
$insertLookup = array_column($insertData, 'prid', 'vendor_id');
$result = [];
foreach ($requestData['vendor_id'] as $index => $vendorId) {
$result[] = [
'prid' => $insertLookup[$vendorId],
'vendor_id' => $vendorId,
'item' => $requestData['item'][$index],
'qty' => $requestData['qty'][$index],
];
}
var_export($result);
Output:
array (
0 =>
array (
'prid' => 4,
'vendor_id' => 1,
'item' => 2,
'qty' => 12,
),
1 =>
array (
'prid' => 4,
'vendor_id' => 1,
'item' => 3,
'qty' => 13,
),
2 =>
array (
'prid' => 5,
'vendor_id' => 2,
'item' => 4,
'qty' => 14,
),
3 =>
array (
'prid' => 5,
'vendor_id' => 2,
'item' => 5,
'qty' => 15,
),
)
You can use the array_merge() function to merge arrays.
array_merge
$merged_array = array_merge($insertData, $requestData);

Why "echo json_encode" is not printing the array?

First i had this:
$myArray = getDatabaseData($p1);
header('Content-Type: application/json');
echo json_encode($myArray );
This was working well, the echo of json data was working correctly.
But now i wanted to add another array data receives data from other query. Like this:
$myArray = getDatabaseData($p1); //returns 2 dimensions array
$myArray2 = getDatabaseData2($p2); //returns 2 dimensions array
$finalArray = array();
$finalArray['data1'] = $myArray;
$finalArray['data2'] = $myArray2;
header('Content-Type: application/json');
echo json_encode($finalArray);
And is not doing the echo.
I've discovered that if i do echo json_encode($myArray); it does the echo.
But if i do echo json_encode($myArray2); it does not.
Note: getDatabaseData function does only one query to the DB. getDatabaseData2 does 4, that are then combined in a single array.
Is it because i am combining multiple db queries in my getDatabaseData2 function?
Here is the print_r of $myArray and $myArray2 :
myArray:
Array
(
[values] => Array
(
[0] => 0
[1] => 2
[2] => 3
[3] => 2
[4] => 7
[5] => 17
[6] => 6
[7] => 5
[8] => 9
[9] => 0
)
[keys] => Array
(
[0] => G. M.
[1] => G. S.
[2] => Cruz.
[3] => At.
[4] => Rem. C.
[5] => Rem. S.
[6] => Fs.
[7] => Rec.
[8] => B. P.
[9] => V. F.
)
)
myArray2:
Array
(
[names] => Array
(
[77] => André
[78] => Daniel
[79] => Rúben
[80] => Ant�nio
[81] => João
[83] => João
)
[nums] => Array
(
[77] => 0
[78] => 2
[79] => 0
[80] => 0
[81] => 0
[83] => 6
)
[nums2] => Array
(
[77] => 0
[78] => 0
[79] => 4
[80] => 0
[81] => 3
[83] => 0
)
)
Thanks for the help.
Here I tried but its working!
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
</head>
<body>
<?php
$arr = array(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5),array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5));
$arr2 = array(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5),array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5),array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5));
$finalArray = [];
$finalArray[] = $arr;
$finalArray[] = $arr2;
echo json_encode($finalArray); die();
?>
</body>
</html>

PHP array with dynamic index

I tried to make table from PHP array. But here all key are dynamic and have also child array
Here is the array structure:
array (
1371618448317 =>
array (
0 =>
array (
0 => '23.77311734',
1 => '90.396355125',
2 => '23.77313316',
3 => '90.396411867187',
4 => '23.77309048',
5 => '90.396419484375',
6 => '23.77307348',
7 => '90.3963645',
),
1 => 20911,
2 =>
array (
1371618713208 =>
array (
0 => 1,
1 => 'BRAC Delivery Centre',
2 => '371/A Shahinbag',
3 => 25,
4 => 91,
5 => 221,
6 => 1,
7 => 11,
8 => 1,
9 => 99,
10 => 1,
11 => 99,
12 => 99,
13 => 99,
14 => 99,
15 => 99,
16 => 1,
),
),
),
1371619410448 =>
array (
0 =>
array (
0 => '23.77894566',
1 => '90.39968559375',
2 => '23.77916362',
3 => '90.400307765625',
4 => '23.77889887',
5 => '90.400401515625',
6 => '23.77870083',
7 => '90.399780515625',
),
1 => 24612,
2 =>
array (
1371619950162 =>
array (
0 => 1,
1 => 'EPI Centre (Govt.)',
2 => ' Mohakhali Road Mohakhali',
3 => 20,
4 => 91,
5 => 11,
6 => 1,
7 => 12,
8 => 1,
9 => 99,
10 => 1,
11 => 99,
12 => 99,
13 => 99,
14 => 99,
15 => 99,
16 => 0,
),
),
),
1371621080807 =>
array (
0 =>
array (
0 => '23.77746206',
1 => '90.399232078125',
2 => '23.77744917',
3 => '90.399623390625',
4 => '23.77712934',
5 => '90.39958940625',
6 => '23.77714809',
7 => '90.399205125',
),
1 => 24566,
2 =>
array (
1371621897771 =>
array (
0 => 1,
1 => 'Society for Assistance to Hearing Impaired Children (SAHIC)',
2 => 'N/A Sattola Road Mohakhali',
3 => 20,
4 => 91,
5 => 222,
6 => 1,
7 => 7,
8 => 1,
9 => 1,
10 => 1,
11 => 1,
12 => 99,
13 => 99,
14 => 99,
15 => 1,
16 => 0,
),
),
),
1371622305777 =>
array (
0 =>
array (
0 => '23.77357261',
1 => '90.36189965625',
2 => '23.77359605',
3 => '90.36197925',
4 => '23.77344028',
5 => '90.36201675',
6 => '23.77341802',
7 => '90.361931296875',
),
1 => 1325,
2 =>
array (
1371622497359 =>
array (
0 => 1,
1 => 'Natoinal Health Care Network',
2 => '3/Ka Pisiculture Housing Society Shamoly',
3 => 29,
4 => 91,
5 => 222,
6 => 1,
7 => 7,
8 => 1,
9 => 99,
10 => 99,
11 => 1,
12 => 99,
13 => 99,
14 => 1,
15 => 1,
16 => 0,
),
),
)
My Desire tale will be look like:
BRAC Delivery Centre 371/A Shahinbag 23.77311734 90.396355125
EPI Centre (Govt.) Mohakhali Road 23.77746206 90.399232078125
from lat long array I always try to collect first lat long.
Can any one give me solution ?
Here is your solution
Input
$array = array(
1371618448317 => array (
array ('23.77311734','90.396355125','23.77313316','90.396411867187','23.77309048','90.396419484375','23.77307348','90.3963645'),
20911,
array ('1371618713208' => array (1,'BRAC Delivery Centre','371/A Shahinbag',25,91,221,1,11,1,99,1,99,99,99,99,99,1))
),
1371619410448 => array (
array ('23.77894566','90.39968559375','23.77916362','90.400307765625','23.77889887','90.400401515625','23.77870083','90.399780515625',),
24612,
array ('1371619950162' => array (1,'EPI Centre (Govt.)',' Mohakhali Road Mohakhali',20,91,11,1,12,1,99,1,99,99,99,99,99,0))
),
1371621080807 => array(
array ('23.77746206','90.399232078125','23.77744917','90.399623390625','23.77712934','90.39958940625','23.77714809','90.399205125'),
24566,
array ('1371621897771' => array (1,
'Society for Assistance to Hearing Impaired Children (SAHIC)','N/A Sattola Road Mohakhali',20,91,222,1,7,1,1,1,1,99,99,99,1,0)
)
),
1371622305777 => array (
array ('23.77357261','90.36189965625','23.77359605','90.36197925','23.77344028','90.36201675','23.77341802','90.361931296875'),
1325,
array ('1371622497359' => array (1,
'Natoinal Health Care Network','3/Ka Pisiculture Housing Society Shamoly',29,91,222,1,7,1,99,99,1,99,99,1,1,0)
)
)
);
Solution
Coordinates are in 1st array.
Name and address is in 3rd.
Coordinates picks easily by $row[0][0].','.$row[0][1]; in given loop below.
For address and name you need to pick key of 3rd array, for this here I used $row[2][key($row[2]);
Now check the code below.
$new_array = array();
$i=0;
foreach($array as $key => $row){
//echo "<pre>";print_r(key($row[2]));
$new[$i]['coordinates'] = $row[0][0].','.$row[0][1];
$new[$i]['name'] = $row[2][key($row[2])][1];
$new[$i]['address'] = $row[2][key($row[2])][2];
$i++;
}
echo "<pre>";print_r($new);
Output
Array
(
[0] => Array
(
[coordinates] => 23.77311734,90.396355125
[name] => BRAC Delivery Centre
[address] => 371/A Shahinbag
)
[1] => Array
(
[coordinates] => 23.77894566,90.39968559375
[name] => EPI Centre (Govt.)
[address] => Mohakhali Road Mohakhali
)
[2] => Array
(
[coordinates] => 23.77746206,90.399232078125
[name] => Society for Assistance to Hearing Impaired Children (SAHIC)
[address] => N/A Sattola Road Mohakhali
)
[3] => Array
(
[coordinates] => 23.77357261,90.36189965625
[name] => Natoinal Health Care Network
[address] => 3/Ka Pisiculture Housing Society Shamoly
)
)
solved myself:
$assoc = true;
$result = json_decode ($json, $assoc);
echo "<table border='1'>";
echo "<tr><td>Hospital Name</td><td>Address</td><td>Lat1</td><td>Long1</td><td>Lat2</td><td>Long1</td><td>Lat3</td><td>Long3</td><td>Lat4</td><td>Long4</td></tr>";
foreach($result as $single_res){
$lat1 = $single_res[0][0];
$long1 = $single_res[0][1];
$lat2 = $single_res[0][2];
$long2 = $single_res[0][3];
$lat3 = $single_res[0][4];
$long3 = $single_res[0][5];
$lat4 = $single_res[0][6];
$long4 = $single_res[0][7];
$key = $single_res[2];
$key_val = array_keys($key);
$key_val = $key_val[0];
$name = $key[$key_val][1];
$address = $key[$key_val][2];

Group array rows by multiple column values and sum another column within each group

I'm trying to group the data in an array of associative arrays by three columns (year, month, grupo) and sum another column (quantity).
Given an array like:
$in = [
['year' => '2010', 'month' => '11', 'grupo' => '2', 'quantity' => 3],
['year' => '2010', 'month' => '11', 'grupo' => '3', 'quantity' => 4],
['year' => '2011', 'month' => '2', 'grupo' => '2', 'quantity' => 4],
['year' => '2011', 'month' => '2', 'grupo' => '2', 'quantity' => 4],
['year' => '2012', 'month' => '3', 'grupo' => '4', 'quantity' => 3]
['year' => '2012', 'month' => '3', 'grupo' => '4', 'quantity' => 3]
];
I want get:
[
['year' => '2010', 'month' => '11', 'grupo' => '2', 'quantity' => 3],
['year' => '2010', 'month' => '11', 'grupo' => '3', 'quantity' => 4],
['year' => '2011', 'month' => '2', 'grupo' => '2', 'quantity' => 8],
['year' => '2012', 'month' => '3', 'grupo' => '4', 'quantity' => 6]
]
I've tried something like this:
$out = array();
foreach ($in as $row) {
if (!isset($out[$row['year']['month']['grupo']])) {
$out[$row['year']['month']['grupo']] = array(
'year' => $row['year'],
'month' => $row['month'],
'grupo' => $row['grupo'],
'quantity' => 0,
);
}
$out[$row['year']['month']['grupo']]['quantity'] += $row['quantity'];
}
$out = array_values($out);
but it fails while trying to group the 3 fields.
I think the earlier answers overlooked the desired result -- the solutions from #hellcode and #Rasclatt create unnecessarily deep structures.
The coding attempt in the question was very close to being right, there was only a flaw in generating unique grouping keys in the first level.
To generate unique grouping keys, you must forge a string from the multiple identifying values in the row. In other words, "compose" a unique value from the three targeted column values -- a composite key.
Code: (Demo)
$result = [];
foreach ($in as $row) {
$compositeKey = implode(array_slice($row, 0, 3));
if (!isset($result[$compositeKey])) {
$result[$compositeKey] = $row;
} else {
$result[$compositeKey]['quantity'] += $row['quantity'];
}
}
var_export(
array_values($result)
);
Try this:
$out = array();
foreach ($in as $row) {
if(! isset($out[$row['year']][$row['month']][$row['grupo']])) {
$out[$row['year']][$row['month']][$row['grupo']]=0;
}
$out[$row['year']][$row['month']][$row['grupo']] += $row['quantity'];
}
print_r($out);
It will output your desired values, but as a multidimensional value array, not as a flat array with key => value pairs:
Array
(
[2010] => Array
(
[11] => Array
(
[2] => 3
[3] => 4
)
)
[2011] => Array
(
[2] => Array
(
[2] => 8
)
)
[2012] => Array
(
[3] => Array
(
[4] => 6
)
)
)
But you can rearrange your array:
$out2 = array();
foreach($out as $year => $year_array) {
foreach($year_array as $month => $month_array) {
foreach($month_array as $grupo => $quantity) {
$out2[] = array('year' => $year, 'month' => $month, 'grupo' => $grupo, 'quantity' => $quantity);
}
}
}
print_r($out2);
This will output:
Array
(
[0] => Array
(
[year] => 2010
[month] => 11
[grupo] => 2
[quantity] => 3
)
[1] => Array
(
[year] => 2010
[month] => 11
[grupo] => 3
[quantity] => 4
)
[2] => Array
(
[year] => 2011
[month] => 2
[grupo] => 2
[quantity] => 8
)
[3] => Array
(
[year] => 2012
[month] => 3
[grupo] => 4
[quantity] => 6
)
)
This will retain values and also give sum.
foreach($in as $row) {
$out[$row['year']][$row['month']][$row['grupo']]['quantity'][] = $row['quantity'];
$out[$row['year']][$row['month']][$row['grupo']]['sum'] = array_sum($out[$row['year']][$row['month']][$row['grupo']]['quantity']);
}
print_r($out);
GIVES
Array
(
[2010] => Array
(
[11] => Array
(
[2] => Array
(
[quantity] => Array
(
[0] => 3
)
[sum] => 3
)
[3] => Array
(
[quantity] => Array
(
[0] => 4
)
[sum] => 4
)
)
)
[2011] => Array
(
[2] => Array
(
[2] => Array
(
[quantity] => Array
(
[0] => 4
[1] => 4
)
[sum] => 8
)
)
)
[2012] => Array
(
[3] => Array
(
[4] => Array
(
[quantity] => Array
(
[0] => 3
[1] => 3
)
[sum] => 6
)
)
)
)

Categories