php Sum specific value from multidimensional array [duplicate] - php

This question already has answers here:
How to sum all column values in multi-dimensional array?
(20 answers)
Closed 1 year ago.
I have array like this :
Array
(
[0] => Array
(
[impr] => 800000
[clicks] => 500
[ctr] => 0.000625
[cvr] => 0.04
[cpc] => 0.14024
[cpm] => 0.08765
[cpa] => 3.51
)
[1] => Array
(
[impr] => 889000
[clicks] => 600
[ctr] => 0.000625
[cvr] => 0.08
[cpc] => 0.34024
[cpm] => 0.08765
[cpa] => 4.41
)
)
I want to sum that array and get result like this
Array
(
[impr] => 1689000
[clicks] => 1100
[ctr] => 0.0025
[cvr] => 0.12
[cpc] => 0.96096
[cpm] => 0.1753
[cpa] => 7.92
)
I trying to using
array_sum()
with looping my array to that array_sum, but I getting error like this
array_sum() expects parameter 1 to be array, integer given
And even try looping with foreach and using += for sum the value, but the result is not I want
the result is 800000889000
Can anyone suggest me the better code for getting my result like I want

First create an array that will contain the sums:
$sumArray = array(
"impr" => 0,
"clicks" => 0,
"ctr" => 0,
"cvr" => 0,
"cpc" => 0,
"cpm" => 0,
"cpa" => 0,
);
Then do the calculating:
foreach ($oldArray as $row)
{
foreach ($rows as $key => $value)
{
$sumArray[$key] += $value;
}
}
Then to view your results, just do:
print_r($sumArray);
NOTE: I am assuming that the keys that you have in your original array don't have the brackets around them, however if the actual key strings do have the brackets, then use the following code for creating $sumArray:
$sumArray = array(
"[impr]" => 0,
"[clicks]" => 0,
"[ctr]" => 0,
"[cvr]" => 0,
"[cpc]" => 0,
"[cpm]" => 0,
"[cpa]" => 0,
);

Related

Defining values to specific indexes of a multidimensional array [duplicate]

This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 1 year ago.
I'm trying to create a function that will assign new values to a specific indexes in a multidimensional array:
I Have the array that looks like this:
data[i]['checkin'];
data[i]['checkout'];
data[i]['content'][x]['price'];
data[i]['content'][x]['profit'];
data[i]['content'][x]['exchangerate'];
first parameter of my function will get the array, And second parameter will get the indexes that I want to redefine:
For example:
function defineNewValues(&$arr, $keys) {
//logic
}
Call the function:
defineNewValues($myArray, [
'data.*.content.*.price' => 0,
'data.*.content.*.profit => 0,
]);
Im beliving that recursion is the key for my problem ,
But not really know how to solve it.
Thank You.
could something like this be okay?
I only ask you to study this code not to implement it, for the simple reason that in the future you may have the same type of problem.
function setValue($key,$value,&$array){
$find_parts = explode(".", $key);
$find = $find_parts[0]??null;
if ($find!=null){
if ($find == "*"){
array_shift($find_parts);
foreach($array as &$sub_array){
setValue(implode(".",$find_parts),$value,$sub_array);
}
}else{
if (count($find_parts)>1){
if (array_key_exists($find,$array)){
array_shift($find_parts);
setValue(implode(".",$find_parts),$value,$array[$find]);
}
}else{
if (array_key_exists($find,$array)){
$array[$find] = $value;
}
}
}
}
}
function defineNewValues(&$arr, $keys) {
foreach($keys as $key=>$value){
setValue($key,$value,$arr);
}
}
$myArray=[
"data"=>[
"a"=>[
"content"=>[
"aa"=>[
"price" => 3,
"profit" => 2,
"other" => 1
],
"ab"=>[
"price" => 3,
"profit" => 2,
"other" => 2
]
]
],
"b"=>[
"content"=>[
"ba"=>[
"price" => 3,
"profit" => 2,
"other" => 4
],
"bb"=>[
"price" => 3,
"profit" => 2,
"other" => 5
]
]
],
]
];
defineNewValues($myArray, [
"data.*.content.*.price" => 0,
"data.*.content.*.profit" => 0,
]);
print_r($myArray);
/* OUTPUT
Array
(
[data] => Array
(
[a] => Array
(
[content] => Array
(
[aa] => Array
(
[price] => 0
[profit] => 0
[other] => 1
)
[ab] => Array
(
[price] => 0
[profit] => 0
[other] => 2
)
)
)
[b] => Array
(
[content] => Array
(
[ba] => Array
(
[price] => 0
[profit] => 0
[other] => 4
)
[bb] => Array
(
[price] => 0
[profit] => 0
[other] => 5
)
)
)
)
)
*/
Because the keys you want to replace only occur at one level of the data, the solution doesn't really need to take the entire array structure into account. You can just replace every price and profit key.
array_walk_recursive($example, function(&$value, $key) {
if (in_array($key, ['price', 'profit'])) {
$value = 0;
}
});
Based on your comment on the other answer, my opinion on the "correct and professional way" is that we should try to solve the problem in the simplest way possible, because simple solutions are easy to maintain.

Sum parts of an array in php

this is quite beyond me. Appreciate some help.
I have an array in php like so:
[0] => Array
(
[cust_id] => 1006
[no_of_subs] => 2
[dlv_id] => 1000
)
[1] => Array
(
[cust_id] => 1011
[no_of_subs] => 3
[dlv_id] => 1000
)
[2] => Array
(
[cust_id] => 1012
[no_of_subs] => 5
[dlv_id] => 1001
)
[3] => Array
(
[cust_id] => 1013
[no_of_subs] => 6
[dlv_id] => 1001
)
I don't need the cust_id field. I just need to group the dlv_id and the sum of no_of_subs for each matching dlv_id. The result should look like this:
[0] => Array
(
[dlv_id] => 1000
[no_of_subs] => 5
)
[1] => Array
(
[cust_id] => 1011
[no_of_subs] => 11
)
Thank you for any help.
I don't understand the downvotes for this question. Am i doing it all wrong? Downvoting without a reason is not helping.
The simplest, most efficient way to group and sum is to perform a single loop and assign temporary associative keys.
When a row is identified as a new dlv_id row, save the two desired elements, otherwise add the no_of_subs value to the pre-existing value.
Optionally, remove the temporary keys with array_values().
Code (Demo)
$array = [
["cust_id" => 1006, "no_of_subs" => 2, "dlv_id" => 1000],
["cust_id" => 1011, "no_of_subs" => 3, "dlv_id" => 1000],
["cust_id" => 1012, "no_of_subs" => 5, "dlv_id" => 1001],
["cust_id" => 1013, "no_of_subs" => 6, "dlv_id" => 1001]
];
foreach ($array as $row) {
if (!isset($result[$row["dlv_id"]])) {
$result[$row["dlv_id"]] = ["dlv_id" => $row["dlv_id"], "no_of_subs" => $row["no_of_subs"]];
} else {
$result[$row["dlv_id"]]["no_of_subs"] += $row["no_of_subs"];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'dlv_id' => 1000,
'no_of_subs' => 5,
),
1 =>
array (
'dlv_id' => 1001,
'no_of_subs' => 11,
),
)
Using array_column function, we can extract out dlv_id and no_of_subs separately in two different arrays, using cust_id as the key.
Now, simply loop over the array of dlv_id, and if matching key found, add the no_of_subs to it, else set the value (for the first time).
We use isset function to check if the key exists already or not.
Try the following:
// your input array is $input_array
// get all dlv_id maintaining the cust_id as index
$dlv_id = array_column($input_array, 'dlv_id', 'cust_id');
// get all no_of_subs maintaining the cust_id as index
$no_of_subs = array_column($input_array, 'no_of_subs', 'cust_id');
$output = array();
foreach ($dlv_id as $key => $value) {
if (isset($output[$value]['dlv_id'])) {
$output[$value]['dlv_id'] += $no_of_subs[$key];
} else {
$output[$value]['dlv_id'] += $no_of_subs[$key];
}
}

get the maximum value of the associative array in php [duplicate]

This question already has answers here:
Hightest value of an associative array
(4 answers)
Closed 4 years ago.
I have the following array
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
I want to get key of the maximum value from the array that is joy from the above array.
Thank you for helping in advance.
$key = array_keys($yourArray,max($yourArray));
You can do this with 2 steps given below:
Get the max value:
$value = max($array);
Get the corresponding key:
$key = array_search($value, $array);
<?php
$array = array(
Array
(
'anger' => 0,
'disgust' => 20,
'fear' => 0,
'joy' => 22.853,
'sadness' => 0,
'surprise' => 0
),
Array
(
'anger' => 0,
'disgust' => 20,
'fear' => 0,
'joy' => 22.853,
'sadness' => 6660,
'surprise' => 0
)
);
for ($i=0; $i < count($array); $i++) {
$maxs = array_keys($array[$i], max($array[$i]));
print_r($maxs);
}
?>
OUTPUT:
Array ( [0] => joy ) Array ( [0] => sadness )
Hope this will help you
Thanks
Muthu
#Niki, above answers are appreciable. Here I've tried to present you in my way. May be, it can be similar to other answers. I will try to find other ways to do the same and update the answer.
Try it online at http://rextester.com/MDGZ18118.
PHP code »
<?php //php 7.0.8
$arr1 = Array
(
"anger" => 0,
"disgust" => 20,
"fear" => 0,
"joy" => 22.853,
"sadness" => 0,
"surprise" => 0,
);
$arr2 = Array
(
"anger" => 0,
"disgust" => 20,
"fear" => 0,
"joy" => 22.853,
"sadness" => 0,
"surprise" => 0,
);
$ret = print_r($arr1); // print_r() returns 1, if we will not store it in any variable then it will be printed on screen.
echo "\n"; // echo "<br>"; for browser
$ret = print_r($arr2);
// Finding key of max element
echo array_search(max($arr1), $arr1);
echo("\n"); // echo "<br>"; for browser
echo array_search(max($arr2), $arr2);
?>
Output »
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
joy
joy

Find similar items in PHP object

I've been trying and trying on this and can't seem to work it out on my own.
So could someone please show me the direction I want to take with this?
I want to be able to implode the object items which contain the string - grade_id.
I've tried getting them all by using array_filter() etc. However seems to not return back the right values.
array_keys() doesn't bring anything back either to try and match array_keys with a preg_match.
I'm just looking for some guidance for this, you don't have to give me a full answered answer, just a point in the right direction.
meeting Object
(
[errors] => 0
[id] => 1
[school_id] => 1
[staff_id] => 2
[grade_id] => 85
[grade_id_2] => 0
[grade_id_3] => 0
[grade_id_4] => 0
[grade_id_5] => 0
[grade_id_6] => 0
[grade_id_7] => 0
[grade_id_8] => 0
[grade_id_9] => 0
[grade_id_10] => 0
[inserted] => 2018-02-19 11:46:13
[updated] => 2018-02-19 12:00:31
)
Result i'm looking for is: (I'm wanting to find a way without using a loop "If possible")
$grade_ids = "85";
You can do this if you convert your object into array:
$array = (array)$object;
/* find keys in array that contain 'grade_id' */
$keys = preg_grep('/grade_id/', array_keys($array));
/* discard other array elements */
$filtered = array_intersect_key($array, array_flip($keys));
$result = implode(',', $filtered);
You can use array_walk_recursive(), I try like this code:
$var = array('meeting'=> array("errors" => 0,
"id" => 1,
"school_id" => 1,
"staff_id" => 2,
"grade_id" => 85,
"grade_id_2" => 0,
"grade_id_3" => 0,
"grade_id_4" => 0,
"grade_id_5" => 0,
"grade_id_6" => 0,
"grade_id_7" => 0,
"grade_id_8" => 0,
"grade_id_9" => 0,
"grade_id_10" => 0,
"inserted" => "2018-02-19 11:46:13",
"updated" => "2018-02-19 12:00:31"));
$uniques = array();
array_walk_recursive($var, function($val, $key) use (&$uniques){
$i=2;
if($key == 'grade_id') {
$uniques[] = $val;
} if($key == 'grade_id_'.$i) {
$uniques[] = $val;
}
$i++;
});
$uniques = array_unique($uniques);
print_r($uniques);
and output is:
Array ( [0] => 85 [1] => 0 )

PHP - trying to sort an array by a numeric field [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 9 years ago.
I have an array of data comprising a 'customer' and a 'Total'. (example below). It is drawn from two different databases.
I need a way to sort the array, based on the Total field, so that the Largest Total is at the top. But so far every thing I have tried has resulted in it assuming that 5 is larger than 32
[5, 32, 25, 16, 11]
What's the easiest way to achieve this? I tried adding intval() to the strcmp function, but it made no difference?
$arrayName = array();
$arrayName[] = array ('customer' => 'Customer1', 'Total' => 25);
$arrayName[] = array ('customer' => 'Customer2', 'Total' => 16);
$arrayName[] = array ('customer' => 'Customer3', 'Total' => 32);
$arrayName[] = array ('customer' => 'Customer4', 'Total' => 5);
$arrayName[] = array ('customer' => 'Customer5', 'Total' => 11);
print_r($arrayName);
print "</br>";
//Sort the Arrray by Total
function arrSort1($b, $a)
{
return strcmp($a['Total']), $b['Total']);
};
usort($arrayName, "arrSort1");
print_r($arrayName);
You're comparing by string but you really want to compare by numeric value. Try:
function arrSort1($b, $a)
{
if ($a['Total'] > $b['Total']) {
return 1;
} else if ($a['Total'] < $b['Total']) {
return -1;
}
return 0;
}
The sorted array will look like this:
Array
(
[0] => Array
(
[customer] => Customer3
[Total] => 32
)
[1] => Array
(
[customer] => Customer1
[Total] => 25
)
[2] => Array
(
[customer] => Customer2
[Total] => 16
)
[3] => Array
(
[customer] => Customer5
[Total] => 11
)
[4] => Array
(
[customer] => Customer4
[Total] => 5
)
)

Categories