Convert an input array into a Google chart JS? - php

I am trying to convert an input to an array which i need to us to display a Google Chart
The input array I got looks like,
$inputArray = [
['date' => '2016-12-10', 'code' => 'P'],
['date' => '2016-12-15', 'code' => 'P'],
['date' => '2017-02-10', 'code' => 'P'],
['date' => '2017-02-14', 'code' => 'P'],
['date' => '2017-03-10', 'code' => 'P'],
['date' => '2017-03-05', 'code' => 'U'],
['date' => '2017-03-11', 'code' => 'U'],
['date' => '2017-03-12', 'code' => 'P'],
['date' => '2017-04-07', 'code' => 'T'],
['date' => '2017-04-18', 'code' => 'P'],
['date' => '2017-04-19', 'code' => 'T'],
['date' => '2017-07-10', 'code' => 'P'],
];
Now I need to group by year and month and sum the code value (4 different values). For these I use a loop like so
function readPerMonth($tmpArray) {
if (empty($tmpArray)) {
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
} else {
$output = [];
foreach ($tmpArray as $value) {
$year = date('Y', strtotime($value['date']));
$month = date('M', strtotime($value['date']));
if (empty($output[$year][$month]))
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
// Check for incident intensity
$output[$year][$month][$value['code']] += 1;
}
}
ksort($output);
ksort($output[$year][$month]);
return $output;
}
and this gives me the Following output, hence last array is in another order???
Array
(
[2017] => Array
(
[Feb] => Array
(
[P] => 11
[T] => 0
[U] => 0
[E] => 0
)
[Mar] => Array
(
[P] => 20
[T] => 0
[U] => 0
[E] => 0
)
[Apr] => Array
(
[P] => 12
[T] => 0
[U] => 0
[E] => 0
)
[May] => Array
(
[P] => 21
[T] => 0
[U] => 0
[E] => 0
)
[Jun] => Array
(
[E] => 0
[P] => 7
[T] => 0
[U] => 1
)
)
)
and I this is an input Array which i need to convert in this JS to plot a stacked Google chart
$output = [
['2016-dec', 2, 0, 0, 0,'2'],
['2017-feb', 2, 0, 0, 0, '2'],
['2017-mar', 2, 0, 2, 0,'4'],
['2017-apr', 1, 1, 0, 0,'2'],
['2017-may', 1, 0, 0, 0, '1'],
];
My php function looks like this
function phpToJS($inputPHP) {
$return = '';
foreach ($inputPHP as $year => $months) {
foreach ($months as $monthValue => $codeValues) {
$sum = 0;
$return .= "['" . $year . " - " . $monthValue . "', ";
foreach ($codeValues as $key => $code) {
if ($key == '') {
$return .= $code;
} else {
$return .= $code . ',';
}
$sum += $code;
}
$return .= ",'" . $sum . "'],";
}
}
return $return;
}
$tmpArr = readPerMonth($inputArray);
$output = phpToJS($tmpArr);
but because of the last Array which isn't in the right order the Google Chart displays wrong.
ps: so sorry to have hit send and not finishing my question title :/

Related

multidimensional array php - sum values with same groupRange

I will try to explain my problem in small examples:
I have a multidimensional array that represents data from the database, lets's say the input looks like this:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 32
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
[2] => Array
(
[groupRange] => 30-44
[value] => 88
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
)
What I want? To sum value, followersFemaleRate, followersMaleRate with the same groupRange, so the output should be this:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 120
[followersFemaleRate] => 34
[followersMaleRate] => 6
)
)
My code:
$RangeArray = [];
foreach($dbProfile->getData() as $d) {
foreach ($d->getGroupPercentages() as $x){
$ageRangeSingleArray['groupRange'] = $x->getGroupRange();
$ageRangeSingleArray['value'] = $x->getValue();
$ageRangeSingleArray['followersFemaleRate'] = $x->getFollowerGenderFemale();
$ageRangeSingleArray['followersMaleRate'] = $x->getFollowerGenderMale();
$RangeArray [] = $ageRangeSingleArray;
}
}
However im stuck, my idea is to first check if groupRage already exists, if yes, sum values for that range, if not add new element groupRange with values, any help with code?
#Salines solution was good, but I offer a simple solution for the beginners...
Another simple solution to your problem:
$input = [
[
'groupRange' => '20-25',
'value' => 12,
'followersFemaleRate' => 12,
'followersMaleRate' => 14,
],
[
'groupRange' => '30-44',
'value' => 88,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
[
'groupRange' => '30-44',
'value' => 32,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
];
$groupRangeHolder = [];
$output = [];
foreach($input as $item) {
if( ! array_key_exists( $item['groupRange'] , $groupRangeHolder ) )
{
$groupRangeHolder[$item['groupRange']]['value'] = $item['value'];
$groupRangeHolder[$item['groupRange']]['followersFemaleRate'] = $item['followersFemaleRate'];
$groupRangeHolder[$item['groupRange']]['followersMaleRate'] = $item['followersMaleRate'];
}
else
{
$groupRangeHolder[$item['groupRange']]['value'] += $item['value'];
$groupRangeHolder[$item['groupRange']]['followersFemaleRate'] += $item['followersFemaleRate'];
$groupRangeHolder[$item['groupRange']]['followersMaleRate'] += $item['followersMaleRate'];
}
}
$cur = 0;
foreach($groupRangeHolder as $key => $values)
{
$output[$cur]['groupRange'] = $key;
$output[$cur]['value'] = $values['value'];
$output[$cur]['followersFemaleRate'] = $values['followersFemaleRate'];
$output[$cur++]['followersMaleRate'] = $values['followersMaleRate'];
}
echo "<pre>";
print_r($output);
echo "</pre>";
try:
$input = [
[
'groupRange' => '20-25',
'value' => 12,
'followersFemaleRate' => 12,
'followersMaleRate' => 14,
],
[
'groupRange' => '30-44',
'value' => 88,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
[
'groupRange' => '30-44',
'value' => 32,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
];
$groupedArray = [];
foreach( $input as $item ){
$groupedArray[$item['groupRange']]['groupRange'] = $item['groupRange'];
$groupedArray[$item['groupRange']]['value'] = ($groupedArray[$item['groupRange']]['value'] ?? 0) + $item['value'];
$groupedArray[$item['groupRange']]['followersFemaleRate'] = $item['followersFemaleRate'];
$groupedArray[$item['groupRange']]['followersMaleRate'] = $item['followersMaleRate'];
}
$output = array_values($groupedArray);
print_r($output);
output:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 120
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
)

Counting values in multidimensional array to new array

I currently have the following array:
Array
(
[0] => Array
(
[declaration_value] => 1
[date] => 2018-07-16
[client_id] => 3
[declaration_id] => 12
)
[1] => Array
(
[declaration_value] => 3
[date] => 2018-07-16
[client_id] => 3
[declaration_id] => 12
)
)
how can i make to get the following array result: (count declaration_value if the same date/client_id/declaration_id )
Array
(
[0] => Array
(
[declaration_value] => 4
[date] => 2018-07-16
[client_id] => 3
[declaration_id] => 12
)
)
$listdb = [
["declaration_value" => 1, "date" => "2018-07-16", "client_id" => 3, "declaration_id" => 12],
["declaration_value" => 2, "date" => "2018-07-16", "client_id" => 2, "declaration_id" => 12],
["declaration_value" => 2, "date" => "2018-07-16", "client_id" => 2, "declaration_id" => 12],
["declaration_value" => 8, "date" => "2018-07-17", "client_id" => 2, "declaration_id" => 12],
["declaration_value" => 3, "date" => "2018-07-16", "client_id" => 3, "declaration_id" => 12],
];
$sameKeys = ["date", "client_id", "declaration_id"];
$sumKeys = ["declaration_value"];
print_r(sum_my($listdb, $sameKeys, $sumKeys));
function sum_my(array $listdb = [], array $sameKeys = [], array $sumKeys = []): array {
$newdb = [];
if (empty($listdb) === true || empty($sameKeys) === true || empty($sumKeys) === true) {
return $newdb;
}
foreach ($listdb as $value) {
$ckKey = "";
foreach ($sameKeys as $sameKey) {
$ckKey .= $value[$sameKey];
}
if (isset($newdb[$ckKey])) {
foreach ($sumKeys as $sumKey) {
$newdb[$ckKey][$sumKey] += $value[$sumKey];
}
} else {
$newdb[$ckKey] = $value;
}
}
return $newdb;
}
Thank you for your tips, I solved it.

php - how to sum values of the multidimensional array

how can I sum values of the key 'NILAI_ANGGARAN'? Note that NILAI_ANGGARAN key is dynamic.
array :
[1350] => Array
(
[495] => Array
(
[NILAI_ANGGARAN] => 11000000
[NILAI_PPN] => 1000000
[PFK] => 0
[TAPERUM] => 0
[LAIN_LAIN] => 0
[NILAI_PPH21] => 500000
[NILAI_PPH22] => 0
[NILAI_PPH23] => 0
[NILAI_PPH4_2] => 0
[DENDA] => 0
[NILAI_BERSIH] => 10500000
)
)
[1300] => Array
(
[488] => Array
(
[NILAI_ANGGARAN] => 15000000
[NILAI_PPN] => 1500000
[PFK] => 0
[TAPERUM] => 0
[LAIN_LAIN] => 0
[NILAI_PPH21] => 0
[NILAI_PPH22] => 450000
[NILAI_PPH23] => 300000
[NILAI_PPH4_2] => 0
[DENDA] => 0
[NILAI_BERSIH] => 15750000
)
)
I've tried solution from How to sum values of the array of the same key? but it getting this error.
Undefined offset: 1350
Update :
This is my desidred result :
Array
(
[NILAI_ANGGARAN] => 26000000
[NILAI_PPN] => 2500000
[PFK] => 0
[TAPERUM] => 0
[LAIN_LAIN] => 0
[NILAI_PPH21] => 500000
[NILAI_PPH22] => 450000
[NILAI_PPH23] => 300000
[NILAI_PPH4_2] => 0
[DENDA] => 0
[NILAI_BERSIH] => 26250000
)
And this is the code I use :
$bruto = array();
foreach($array as $data => $key) {
foreach($key as $k => $value) {
foreach($value as $v => $isi) {
$bruto[$k]+=$value;
}
}
}
print_r($bruto);
Can anyone help me with another solution?
Thx
You can try this
Array:
$multi_dimentional_array = array (
'1350' => array
(
'495' => array
(
'NILAI_ANGGARAN' => 11000000,
'NILAI_PPN' => 1000000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 500000,
'NILAI_PPH22' => 0,
'NILAI_PPH23' => 0,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 10500000
)
),
'1300' => array
(
'488' => array
(
'NILAI_ANGGARAN' => 15000000,
'NILAI_PPN' => 1500000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 0,
'NILAI_PPH22' => 450000,
'NILAI_PPH23' => 300000,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 15750000
)
)
);
Get sum values of the key 'NILAI_ANGGARAN' Code:
$NILAI_ANGGARAN_TOTAL = 0;
foreach( $multi_dimentional_array as $fkey=>$smarray )
{
foreach ($smarray as $skey => $value) {
// Empty check
if ( !empty( $value['NILAI_ANGGARAN'] ) ){
$NILAI_ANGGARAN_TOTAL += $value['NILAI_ANGGARAN'];
}
}
}
echo "Sum of NILAI_ANGGARAN is :{$NILAI_ANGGARAN_TOTAL}";
Result:Sum of NILAI_ANGGARAN is :26000000
Let's consider the multi-dimensional array to be $array.
You simply need to use nested loop here.
Try this:
$sum = 0;
foreach ($array as $arr) {
foreach ($arr as $a) {
$sum += $a['NILAI_ANGGARAN'];
}
}
echo $sum;
Hope this helps.
Peace! xD
You also need to check if value with index 'NILAI_ANGGARAN' exists, otherwise PHP shows undefined offset error!
<?php
$array = array (
'1350' => array
(
'495' => array
(
'NILAI_ANGGARAN' => 11000000,
'NILAI_PPN' => 1000000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 500000,
'NILAI_PPH22' => 0,
'NILAI_PPH23' => 0,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 10500000
)
),
'1300' => array
(
'488' => array
(
'NILAI_ANGGARAN' => 15000000,
'NILAI_PPN' => 1500000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 0,
'NILAI_PPH22' => 450000,
'NILAI_PPH23' => 300000,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 15750000
)
)
);
$sum = 0;
foreach($array as $key => $subarray)
{
foreach($subarray as $subsubarrray)
{
if(isset($subsubarrray['NILAI_ANGGARAN'])) //check if isset
$sum += $subsubarrray['NILAI_ANGGARAN'];
}
}
var_dump($sum);
you can use advance php for the same. Using RecursiveArrayIterator and RecursiveIteratorIterator it can be done easily:
$multi_dimentional_array = array (
'1350' => array
(
'495' => array
(
'NILAI_ANGGARAN' => 11000000,
'NILAI_PPN' => 1000000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 500000,
'NILAI_PPH22' => 0,
'NILAI_PPH23' => 0,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 10500000
)
),
'1300' => array
(
'488' => array
(
'NILAI_ANGGARAN' => 15000000,
'NILAI_PPN' => 1500000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 0,
'NILAI_PPH22' => 450000,
'NILAI_PPH23' => 300000,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 15750000
)
)
);
$sum = 0;
$k_value = 'NILAI_ANGGARAN';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($multi_dimentional_array));
foreach ($iterator as $key => $value) {
if($key == $k_value){
$sum +=$value;
}
}
echo "SUM of $k_value is $sum";
Output
SUM of NILAI_ANGGARAN is 26000000
use this code :
$sum_arr = array();
foreach($main as $m_item){
foreach($sub as $s_item){
foreach($s_item as $skey => $value){
$sum_arr[$skey] += $value;
}
}
}
use this code it will in $sum_arr is array of all element and its also in array format
try this it will work 100% :)

Extract a row by value from php array

This is my array:
Array (
[0] => Array ( [SocketID] => 1 [SocketName] => Name [SocketDecimal] => 0 [SocketHex] => 00 [SocketAtt] => 1 [Category] => 1 [Value] => 100 [Procentage] => 0 )
[1] => Array ( [SocketID] => 2 [SocketName] => Name2 [SocketDecimal] => 50 [SocketHex] => 32 [SocketAtt] => 1 [Category] => 1 [Value] => 800 [Procentage] => 0 )
[2] => Array ( [SocketID] => 3 [SocketName] => Name3 [SocketDecimal] => 100 [SocketHex] => 64 [SocketAtt] => 1 [Category] => 1 [Value] => 60 [Procentage] => 0 )
)
How can I extract a row by SocketDecimal?
For example: I want to extract row where SocketDecimal = 50 and make new an array only with that row.
foreach($array as $entry) {
if($entry['SocketDecimal'] == 50)
$newArr[] = $entry;
}
$newArr will contain the desired "row". Of course you can manipulate the if-statement depending on which "row" (I'd just call it array entry) you want to extract.
It's not the best way for big data! It's easy for deep multiarrays.
$arr = array(
array('socket_id'=>1,'name'=>'test1'),
array('socket_id'=>2,'name'=>'test2'),
array('socket_id'=>3,'name'=>'test3'),
array('socket_id'=>2,'name'=>'test4')
);
$newArr = array();
foreach($arr as $row){
foreach($row as $key=>$r){
if($key == 'socket_id' && $r==2)
$newArr[] = $row;
}
}
print_r($newArr);
$result = array();
foreach($input as $i){
if($i['SocketDecimal']==50)
$result[]=$i;
}
You can do it by this method
foreach ($yourarray as $key => $value){
$newarray = array("SocketDecimal"=>$value["SocketDecimal"];
}
print_r($newarray);
If your result array is like given below
$arr = array(
array( 'SocketID' => 1, 'SocketName' => 'Name', 'SocketDecimal' => 0, 'SocketHex' => 0, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 100, 'Procentage' => 0 ),
array ( 'SocketID' => 2, 'SocketName' => 'Name2', 'SocketDecimal' => 50, 'SocketHex' => 32, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 800, 'Procentage' => 0 ),
array ( 'SocketID' => 3, 'SocketName' => 'Name3', 'SocketDecimal' => 100, 'SocketHex' => 64, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 60, 'Procentage' => 0 )
);
print_r($arr);
Get row for SocketDecimal=50 by following loop:
<pre>
$resultArr = '';
foreach($arr as $recordSet)
{
if($recordSet['SocketDecimal'] == 50)
{
$resultArr[] = $recordSet;
break;
}
}
</pre>
print_r($resultArr);
break foreach loop so that it will not traverse for all the array when SocketDecimal(50) founded.
You can use array_column + array_search combo
$array = Array (
"0" => Array ( "SocketID" => 1, "SocketName" => "Name", "SocketDecimal" => 0, "SocketHex" => 00, "SocketAtt" => 1, "Category" => 1, "Value" => 100, "Procentage" => 0 ) ,
"1" => Array ( "SocketID" => 2, "SocketName" => "Name2", "SocketDecimal" => 50, "SocketHex" => 32, "SocketAtt" => 1, "Category" => 1, "Value" => 800, "Procentage" => 0 ),
"2" => Array ( "SocketID" => 3, "SocketName" => "Name3", "SocketDecimal" => 100, "SocketHex" => 64, "SocketAtt" => 1, "Category" => 1, "Value" => 60 ,"Procentage" => 0 )
);
var_dump($array[array_search(50,array_column($array,'SocketDecimal'))]);

Join 2 multidimensional array

$items = array(
array(
'id' => 0,
'name' => 'Simple Sword',
'type' => 'weapon',
'price' => 200,
'value1' => 5,
'value2' => 10,
'value3' => 0,
'value4' => 0,
'value5' => 0
),
array(
'id' => 1,
'name' => 'Iron Sword',
'type' => 'weapon',
'price' => 500,
'value1' => 0,
'value2' => 0,
'value3' => 0,
'value4' => 0,
'value5' => 0
)
);
$inventory = array(
array(
'item' => 0,
'slot' => 1,
'value1' => 0,
'value2' => 0,
'value3' => 0,
'value4' => 0,
'value5' => 0,
'equipped' => 0
),
array(
'item' => 1,
'slot' => 2,
'value1' => 0,
'value2' => 0,
'value3' => 0,
'value4' => 0,
'value5' => 0,
'equipped' => 1
)
);
What I need is to join these 2 multidimensional arrays, or take the values, keys etc from the "Items" array and put it in the Inventory array where the "item" id matches the id from the Items array. Similiar to a INNER JOIN statement in SQL. How? I can't figure it out.
Secondly, I am trying to print out the $inventory array, I tried the following, but It didn't work:
foreach ($inventory as $a) {
foreach ($a as $b) {
echo $b['item'];
}
}
It gives me no output.
a little help with your second problem:
foreach ($inventory as $a => $b) {
echo $b['item'];
}
}
As for first question Zulkhaery Basrul gave good answer. I would also consider putting break statement if relation is one-to-one:
if($val['item'] == $items[$key]['id']) {
$newarr[] = array_merge($items[$key],$val);
break;
}
As for second question:
foreach ($inventory as $invKey => $aInventoryItem) {
echo $aInventoryItem['item'] . "\n";
}
I think you can just do this in order to echo the item from inventory:
foreach($inventory as $inv) {
echo $inv['item'];
}
foreach($inventory as $key=>$val)
{
if($val['item'] == $items[$key]['id'])
{
$newarr[] = array_merge($items[$key],$val);
}
}
check $newarr[] using print_r($newarr), here the output :
Array
(
[0] => Array
(
[id] => 0
[name] => Simple Sword
[type] => weapon
[price] => 200
[value1] => 0
[value2] => 0
[value3] => 0
[value4] => 0
[value5] => 0
[item] => 0
[slot] => 1
[equipped] => 0
)
[1] => Array
(
[id] => 1
[name] => Iron Sword
[type] => weapon
[price] => 500
[value1] => 0
[value2] => 0
[value3] => 0
[value4] => 0
[value5] => 0
[item] => 1
[slot] => 2
[equipped] => 1
)
)
Second question, to print out the $inventory array:
foreach ($inventory as $a)
{
echo $a['item'];
echo $a['slot'];
echo $a['value1'];
//...etc
}
I believe this function is what you're looking for:
// Join Arrays on Keys
function array_join($original, $merge, $on) {
if (!is_array($on)) $on = array($on);
foreach ($merge as $right) {
foreach ($original as $index => $left) {
foreach ($on as $from_key => $to_key) {
if (!isset($original[$index][$from_key])
|| !isset($right[$to_key])
|| $original[$index][$from_key] != $right[$to_key])
continue 2;
}
$original[$index] = array_merge($left, $right);
}
}
return $original;
}
Usage for your scenario:
print_r(array_join($items, $inventory, array('id' => 'item')));
I've asked the community for help with optimizing the LEFT JOIN version of the function here (the only differences are $remove unset and array_merge): How can I optimize my array_join (simulates a LEFT JOIN) function?

Categories