Multiple array data in php and get the SUM - php

I am using Codeigniter and I have a function like this .
function total_income(){
$data['total_income'] = $this->mod_products->total_income();
echo"<pre>";
print_r($data['total_income']);
}
The above code return an array like this.
Array
(
[0] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[1] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[2] => stdClass Object
(
[sub_product_price] => 50
[quantity] => 15
)
[3] => stdClass Object
(
[sub_product_price] => 500
[quantity] => 5
)
)
Now I want to get the [sub_product_price] and multiply that value with [quantity] .Then I want to get the array_sum. I don't have an idea how to do that. Could some one help me It would be grate ,
Cheers!! Rob

$sum = 0;
foreach ($array as $obj) {
$sum += ($obj->quantity * $obj->sub_product_price);
}

Add the all values after multiplication in an empty array and use array_sum() to get the final value.
$temp = array();
foreach($data['total_income'] as $in)
{
$temp[] = $in->sub_product_price * $in->quantity;
}
$total = array_sum($temp);
Explanation:
array_sum() returns the sum of all the values of an array.
Example,
$array = array(4,5,6);
echo array_sum($array); // 15

Related

Could not sort json object by same key using PHP

I am trying to sort json object by same key and merge the value part using PHP but not getting the result as expected. My code is below:
$customArr=[{"attribute_code":"budget","value":"141"},{"attribute_code":"restaurants","value":"166"},{"attribute_code":"food_type","value":"172"},{"attribute_code":"budget","value":"142"},{"attribute_code":"restaurants","value":"168"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"143"},{"attribute_code":"restaurants","value":"170"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"162"},{"attribute_code":"restaurants","value":"171"},{"attribute_code":"food_type","value":"172"}]
function sortByName($a, $b){
$a = $a['attribute_code'];
$b = $b['attribute_code'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
usort($customArr, 'sortByName');
Here I need if attribute_code is same then push the respective value into one array and also the duplicate value should not be there. The expected result is given below.
[{"attribute_code":"budget","value":[141,142,143,162]},{}.....]
But in my case the expected result not coming.
Using array_reduce() you can try it. array_reduce() callback takes two arguments, who's first argument is the old/previous iteration value and second argument is the current iteration value/element.
So using this function we can holds our current iteration values to the previous iteration value (total values).
array_reduce() iteratively reduce the array to a single value using a callback function.
$customArr = json_decode('[{"attribute_code":"budget","value":"141"},{"attribute_code":"restaurants","value":"166"},{"attribute_code":"food_type","value":"172"},{"attribute_code":"budget","value":"142"},{"attribute_code":"restaurants","value":"168"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"143"},{"attribute_code":"restaurants","value":"170"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"162"},{"attribute_code":"restaurants","value":"171"},{"attribute_code":"food_type","value":"172"}]', true);
$data = array_reduce($customArr, function ($acc, $new) {
if (isset($acc[$new['attribute_code']])) {
$old_value = $acc[$new['attribute_code']]['value'];
$acc[$new['attribute_code']]['value'] = array_unique(is_array($old_value) ? array_merge($old_value, [$new['value']]) : [$old_value, $new['value']]);
} else {
$acc[$new['attribute_code']] = $new;
}
return $acc;
}, []);
ksort($data);
echo '<pre>', json_encode(array_values($data));
Working demo.
At the moment you are just sorting the entries according to the attribute_code and doing nothing about merging the data items.
This code creates a new output array (keyed it by the attribute_code), if the code is already there it adds the value into the list of existing values, if not it adds a new item in, creating the value as an array (with the first item in). Lastly it uses ksort() to sort the items.
If you don't need these keys, then array_values() will give you a plain array (as in the output)...
$json='[{"attribute_code":"budget","value":"141"},{"attribute_code":"restaurants","value":"166"},{"attribute_code":"food_type","value":"172"},{"attribute_code":"budget","value":"142"},{"attribute_code":"restaurants","value":"168"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"143"},{"attribute_code":"restaurants","value":"170"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"162"},{"attribute_code":"restaurants","value":"171"},{"attribute_code":"food_type","value":"172"}]';
$customArr = json_decode($json, true);
$output = [];
foreach ( $customArr as $attribute ) {
if ( isset ( $output[$attribute['attribute_code']])) {
$output[$attribute['attribute_code']]['value'][] = $attribute['value'];
}
else {
$output[$attribute['attribute_code']] = ["attribute_code"=>$attribute['attribute_code'],
"value"=> [$attribute['value']]];
}
}
// Make sure values are unique
foreach ( $output as $code => $value ){
$output[$code]['value'] = array_unique($output[$code]['value']);
}
ksort($output);
print_r(array_values($output));
gives...
Array
(
[0] => Array
(
[attribute_code] => budget
[value] => Array
(
[0] => 141
[1] => 142
[2] => 143
[3] => 162
)
)
[1] => Array
(
[attribute_code] => food_type
[value] => Array
(
[0] => 172
[1] => 173
)
)
[2] => Array
(
[attribute_code] => restaurants
[value] => Array
(
[0] => 166
[1] => 168
[2] => 170
[3] => 171
)
)
)
You have a JSON string, not an array.
$jsonString = '[{"attribute_code":"budget","value":"141"},{"attribute_code":"restaurants","value":"166"},{"attribute_code":"food_type","value":"172"},{"attribute_code":"budget","value":"142"},{"attribute_code":"restaurants","value":"168"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"143"},{"attribute_code":"restaurants","value":"170"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"162"},{"attribute_code":"restaurants","value":"171"},{"attribute_code":"food_type","value":"172"}]';
$customArr = json_decode($jsonString, true);
function sortByName($a, $b)
{
$a = $a['attribute_code'];
$b = $b['attribute_code'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
usort($customArr, 'sortByName');
The similar solution as above, but a little different using a temp variable and in a single iteration:
<?php
$str='[{"attribute_code":"budget","value":"141"},{"attribute_code":"restaurants","value":"166"},{"attribute_code":"food_type","value":"172"},{"attribute_code":"budget","value":"142"},{"attribute_code":"restaurants","value":"168"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"143"},{"attribute_code":"restaurants","value":"170"},{"attribute_code":"food_type","value":"173"},{"attribute_code":"budget","value":"162"},{"attribute_code":"restaurants","value":"171"},{"attribute_code":"food_type","value":"172"}]';
$arr = json_decode($str,true);
$temp = $result= [];
foreach($arr as $key=>$customer){
if(in_array($customer['attribute_code'], $temp)){
$index=array_search($customer['attribute_code'],$temp);
if(!in_array($customer['value'],$result[$index]['value'])){
$result[$index]['value'][]=$customer['value'];
}
}else {
$temp[]=$customer['attribute_code'];
$result[]=[
'attribute_code'=>$customer['attribute_code'],
'value'=>[$customer['value']]
];
}
}
unset($temp);
print_r($result);
echo json_encode($result);
?>
Result :
Array
(
[0] => Array
(
[attribute_code] => budget
[value] => Array
(
[0] => 141
[1] => 142
[2] => 143
[3] => 162
)
)
[1] => Array
(
[attribute_code] => restaurants
[value] => Array
(
[0] => 166
[1] => 168
[2] => 170
[3] => 171
)
)
[2] => Array
(
[attribute_code] => food_type
[value] => Array
(
[0] => 172
[1] => 173
)
)
)
JSON ENCODED RESPONSE
[{"attribute_code":"budget","value":["141","142","143","162"]},{"attribute_code":"restaurants","value":["166","168","170","171"]},{"attribute_code":"food_type","value":["172","173"]}]

Sum array on key - possible or is the array not structured in a good way?

Have built the following array based on an accounting file and want to create sums from the [trans] subarray for all accounts based on the amount. Looked into array_column but have a feeling the array is not built correctly or in an efficient way for this? Any thoughts/suggestions much appreciated.
//Clarification
Hi! Many thanks. I was probably a bit unclear. For the total population of [trans] I want to sum the amount where the account is the same. So the array above would generate:
[1930] = -150.47-431.63
[5912] = 150.47
etc
[#VER] => Array
(
[A1] => Array
(
[verdatum] => 20150107
[vertext] => GOOGLE
[trans] => Array
(
[0] => Array
(
[account] => 1930
[amount] => -150.47
)
[1] => Array
(
[account] => 5912
[amount] => 150.47
)
[2] => Array
(
[account] => 2645
[amount] => 37.62
)
[3] => Array
(
[account] => 2614
[amount] => -37.62
)
)
)
[A2] => Array
(
[verdatum] => 20150118
[vertext] => Post
[trans] => Array
(
[0] => Array
(
[account] => 1930
[amount] => -431.63
)
[1] => Array
(
[account] => 5710
[amount] => 345.30
)
[2] => Array
(
[account] => 2641
[amount] => 86.33
)
)
)
)
Its simply a foreach loop to acheive your expected sum of amount
$temp = array();
$new = array();
foreach($arr as $key=>$value){
foreach($value["trans"] as $key2=>$value2){
if(in_array($value2["account"], $temp)){
$new[$value2["account"]] += $value2["amount"];
}else {
$new[$value2["account"]] = $value2["amount"];
$temp[] = $value2["account"];
}
}
}
print_r($new);
Live demo : https://eval.in/857342
Output will be
Array
(
[1930] => -582.1
[5912] => 150.47
[2645] => 37.62
[2614] => -37.62
[5710] => 345.3
[2641] => 86.33
)
$grand_total = 0;
array_walk($my_array['#VER'],function (&$ver) use (&$grand_total){
$ver['total_amount'] = 0;
foreach($ver['trans'] as $trans){
$ver['total_amount'] += $trans['amount'];
}
$grand_total += $ver['total_amount'];
});
So, simply loop through your "VER" then loop again on each trans. As simple as that. I've used both array_walk and foreach techniques, mainly to show you the two ways. You could prefer use two foreach, or two array_walk, it would work.
This script adds to a $grand_total variable, and also store the total of all transactions into each VER entry.
Modified:
$grand_total = 0;
array_walk($urarr['#VER'],function (&$ver) use (&$grand_total){
foreach($ver['trans'] as $trans){
if ($trans['amount'] < 0){
$neg += abs($trans['amount']);
}else{
$pos += abs($trans['amount']);
}
}
$diff = ($pos < $neg) ? "-".($neg - $pos) : ($pos - $neg);
$grand_total += $diff;
});
print $grand_total;

How to get SUM value in a array?

I have 2 elements which has the value of member which is 5
I want to get the sum of all value of member
[member] => 5 + [member] => 5 = 10
The output should be 10
This is my array
Array
(
[0] => Array
(
[membUid] => 0090000816
[service_id] => 0
[member] => 5
)
[1] => Array
(
[membUid] => 0090000867
[service_id] => 0
[member] => 5
)
)
This is my code:
foreach($result['content'] as $res){
sum($res['member']);
}
Does this work?
$sum = 0;
foreach ($result as $res) {
$sum += $res['member'];
}
echo $sum;
alternative solution, with array_sum & array_map functions
echo array_sum(array_map(function($i){return $i["member"];},$result['content']));

Counting unique arrays inside the array in PHP?

I have some array containing other arrays:
Array
(
[0] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[1] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[2] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 24
[madeDatetime:protected] => 2011-04-18 11:31:26
[stake:protected] => 13.00
[status:protected] => 6
)
)
What's the best way of counting unique arrays?
Off the top of my head you could try:
$hashes = array();
$uniques = 0;
foreach($array as $slip) {
$hash = sha1(serialize($slip));
if(!in_array($hash, $hashes)) {
++$uniques;
$hashes[] = $hash;
}
}
var_dump($uniques); // prints total number of unique objects.
Edit:
#biakaveron's idea looks better though and could be adapted to:
$uniques = count(array_unique($array, SORT_REGULAR));
var_dump($uniques); // prints total number of unique objects.
This previous question has various solutions for removing duplicate arrays from within an array. If you implement any of them and then use sizeof() on the returned array you will have your solution.
eg:
<?php
$yourarray = array();
$tmp = array ();
foreach ($yourarray as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
echo sizeof($tmp);
?>

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories