Looping through array and totalling values - php

I require a bit of assistance, if someone would be kind enough to help.
I have an array with values, which I want to loop through, and if any of the 'user_id values' are the same then to total the 'max_score' value of the duplicate user id's.
Array
(
[0] => Array
(
[user_id] => 2
[max_score] => 10081
)
[1] => Array
(
[user_id] => 1
[max_score] => 8774
)
[2] => Array
(
[user_id] => 2
[max_score] => 5477
)
[3] => Array
(
[user_id] => 3
[max_score] => 5267
)
[4] => Array
(
[user_id] => 1
[max_score] => 5010
)
)
Would anyone know how to accomplish this?
Many thanks.

$totals = array();
foreach ($your_array_values as $v) {
$id = $v['user_id'];
if (isset($totals[$id])) {
$totals[$id] += $v['max_score'];
} else {
$totals[$id] = $v['max_score'];
}
}

you need a second array with the user ids as key. You can do it like this:
$scoresums = array();
foreach ($yourarray AS $user_score) {
if (!isset($scoresums[$user_score['user_id']])) $scoresums[$user_score['user_id']] = 0;
$scoresums[$user_score['user_id']] += $user_score['max_score'];
}
The third line will prevent php from throwing notices.

Related

PHP replace multiple values from an array to another one

I want to insert the values from the first array inside the second array, where the key's name is [cost]:
$newcosts
Array (
[0] => 52.68
[1] => 7414.68
[2] => 2471.56
)
$mainarray
[0] => Array (
[id] => 2
[date] => 15.12.2020
[cost] => 60.00
)
[1] => Array (
[id] => 1
[date] => 22.12.2020
[cost] => 60.00
)
[2] => Array (
[id] => 3
[date] => 24.12.2020
[cost] => 22.00
)
I tried the following:
foreach ($mainarray as $key => $value) {
$values[] = $value['cost'];
$new_array[] = str_replace($values, $newcosts, $value);
}
for some reason, this is not showing the right data and sometime they get repeated. this is an example:
[0] => Array (
[id] => 2
[date] => 15.12.2020
[cost] => 52.68
)
[1] => Array (
[id] => 1
[date] => 22.12.2020
[cost] => 52.68
)
[2] => Array (
[id] => 3
[date] => 24.12.2020
[cost] => 2471.56
)
Hope someone could help me on that. Thank you very much!
Just use the mainarray's index to replace the $newcosts into the array.
foreach ($mainarray as $index => $subarray) {
$mainarray[$index]['cost'] = $newcosts[$index];
}
Because you will have an unused variable $subarray this way, it would be nicer to use a for loop:
for ($i = 0; $i < count($mainarray); $i++) {
$mainarray[$i]['cost'] = $newcosts[$i];
}
user foreach to get value of $newcosts and then
in loop replace value of price by id
in foreach loop you shuld replace value of $mainarray
foreach($newcosts as $itme => $value){
$mainarray [$itme ]['cost'] = $value;
}
Why are you using str_replace to replace float value ?
You can also index your array like this
for ($idx = 0; $idx <= count($mainarray); $idx++) {
$mainarray[$idx]['cost'] = $mainarray[$idx];
}
edit : same solution as above
A function-based equivalent to classic loops is to call array_walk() and modify the rows by reference. Using arrow function syntax (since PHP7.4) means you don't have to use use().
Code: (Demo)
array_walk(
$mainarray,
fn(&$row, $i) => $row['cost'] = $newcosts[$i]
);
var_export($mainarray);

count same categories from array and Store in new array with its count and category name

I have one array which I am getting from database query response.
Now I want to count same categories and print in option_name array.
I have tried it with different array functions but want get desire output.
I have one idea to take new array and push it with foreach loop but not much idea of how can i achieve using code. Please help me to solve it.
Array
(
[0] => Array
(
[CNC] => Array
(
[id] => 5
[category_id] => 68
)
[GVO] => Array
(
[option_name] => Actors
)
)
[1] => Array
(
[CNC] => Array
(
[id] => 11
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[2] => Array
(
[CNC] => Array
(
[id] => 3
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[3] => Array
(
[CNC] => Array
(
[id] => 4
[category_id] => 74
)
[GVO] => Array
(
[option_name] => Musician
)
)
[4] => Array
(
[CNC] => Array
(
[id] => 7
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
[5] => Array
(
[CNC] => Array
(
[id] => 6
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
)
Desire Output:
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Thanks in advance!
You simply need to loop through the array using foreach like as
$result = [];
foreach($arr as $k => $v){
if(isset($result[$v['GVO']['option_name']])){
$result[$v['GVO']['option_name']] += 1;
}else{
$result[$v['GVO']['option_name']] = 1;
}
}
print_R($result);
You can count the option_name values by incrementing a counter in an associative array where the key is the option_name:
$counts = [];
foreach($array as $v) {
if(!isset($counts[$v['GVO']['option_name']])) {
$counts[$v['GVO']['option_name']] = 0;
}
$counts[$v['GVO']['option_name']]++;
}
print_r($counts);
Try this:
$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
if(in_array($value, $new_array)){
$new_array[$value] = $new_array[$value]+1;
}else{
$new_array[$value] = 1;
}
}
Output
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)

list duplicates in PHP Array

i have a new problem and my mind is burning, i have an array in php
$test = array();
Array
(
[0] => Array
(
[account] => 14319896
[value] => 725.57
[id] => 280
)
[1] => Array
(
[account] => 163157
[value] => -723.57
[id] => 283
)
[2] => Array
(
[account] => 163157
[value] => 723.57
[id] => 284
)
[3] => Array
(
[account] => 161817
[value] => -723.57
[id] => 285
)
)
i need the accounts, they are more than one in this array, in this example i need $test[1][id] and $test[2][id]
have you an idea? i have no idea more at this time.
Thanks for your help.
Use the account number as key in a new array, count each entry and then take the items with a count > 1
$dupes = array();
foreach($array as $account) {
++$dupes[$account['account']];
}
$dupes = array_filter($dupes, function($count) { return $count > 1; });
Editing to answer the comments below the question …
If you want the IDs (or keys) of the duplicates, do not store the count directly, but use another array instead.
$dupes = array();
foreach($array as $key => $account) {
if(!array_key_exists($account, $dupes))
$dupes[$account['account']] = array();
$dupes[$account['account']][] = $account['id']; // or: = $key
}
$dupes = array_filter($dupes, function($ids) { return count($ids) > 1; });
You should change your architecture to have a associative array where keys are account number organized like that :
Array
(
[14319896] => Array
(
[0]=>Array(
[value] => 725.57
[id] => 280
)
)
[163157] => Array
(
[0]=>Array(
[value] => -723.57
[id] => 283
)
[1]=>Array(
[value] => 723.57
[id] => 284
)
)
[161817] => Array
(
[0]=>Array(
[value] => -723.57
[id] => 285
)
)
)
$dupes = array();
foreach($array as $key => $account) {
$dupes[$account['account']][] = array($account['id'],$account['value']);
}
Whith that architecture you can get everything you want thanks to array_filter :
$dups = array_filter($dupes, function($account){ return count($account)>1;});

PHP combine array based on value of particular element

I have an array that looks like this
Array (
[0] => Array
(
[id] => 123
[count] => 1
)
[1] => Array
(
[id] => 123
[count] => 3
)
[2] => Array
(
[id] => 513
[count] => 0
)
[3] => Array
(
[id] => 561
[count] => 1
)
[4] => Array
(
[id] => 613
[count] => 7
)
)
What I want to do is create a new array, that totals the count where the id values are the same. So for example, the new array would look like this:
Array (
[0] => Array
(
[id] => 123
[count] => 4
)
[1] => Array
(
[id] => 513
[count] => 0
)
[2] => Array
(
[id] => 561
[count] => 1
)
[3] => Array
(
[id] => 613
[count] => 7
)
)
Would anyone know a good method to do this?
Thank you!
Short and simple:
$new_array = array();
foreach($data_array as $value) {
if(array_key_exists($value['id'], $new_array)) {
$new_array[$value['id']] += $value['count'];
} else {
$new_array[$value['id']] = $value['count'];
}
}
echo print_r($new_array,true);
I made it id => value since there didn't seem to need another array for data when the id could be used as the array's key.
Any reason why you are not making an associative array of id => count
You can do it with the following function (I didn't tested the code, but it should work ):
function get_count_array($arr) {
$new_array = array();
foreach($arr as $item) {
$found = false;
//loop through all the current new items to check if we already have it
for($i = 0; $i < count($new_array); $i++) {
//do we have it?
if($new_array[$i]['id'] == $item['id']) {
$new_array[$i]['count'] += 1;
$found = true;
break;
}
}
if(!$found) {
$new_array[] = array('id' => $item['id'], 'count' => 0);
}
}
return $new_array;
}

php - array_combine or array_merge?

I'm sure this is easy for someone well-versed in php, but I've made the mistake of overloading my brain, so now I'm really confused as to whether I should use array_combine, array_merge, or something else... I've been googling and reading php.net for 4 hours and I think I'm just confusing myself even more...
Essentially, I just want to combine an array while keeping the keys?
//Here are the original arrays
[field_sreference] => Array
(
[0] => Array
(
[nid] => 28
)
[1] => Array
(
[nid] => 28
)
[2] => Array
(
[nid] => 29
)
)
[field_idelta] => Array
(
[0] => Array
(
[value] => 0
)
[1] => Array
(
[value] => 1
)
[2] => Array
(
[value] => 0
)
)
[field_iswitch] => Array
(
[0] => Array
(
[value] => 0
)
[1] => Array
(
[value] => 0
)
[2] => Array
(
[value] => 0
)
)
//Here is what I'm trying to achieve:
[combinedarray] => Array
(
[0] => Array
(
[nid] => 28
[idelta] => 0
[iswitch] => 0
)
[1] => Array
(
[nid] => 28
[idelta] => 1
[iswitch] => 0
)
[2] => Array
(
[nid] => 29
[idelta] => 0
[iswitch] => 0
)
)
You can solve this is O(n) by simply iterating the arrays...
$combinedarray = array();
$len = count($field_sreference);
for ($i = 0; $i < $len; $i++) {
$combinedarray[] = array("nid" => $field_sreference[$i]['nid'],
"idelta" => $filed_idelta[$i]['value'],
"iswitch" => $field_iswitch[$i]['value']);
}
This assumes, the 3 arrays are all of equal length.
A bit quickly typed, but this should work:
$result = array();
foreach ($arrays as $array)
{
foreach ($array as $index => $data)
{
$result[$index] += $data;
}
}
As you have not provided some input array in some easy form, you need to test it on your own. Let's say it's pseudo-code and I leave it here as an exercise. The + operator is the array union operator.

Categories