Sum like values in Multi-Dimensional array php - php

I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.

You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b

The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.

Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;

You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}

$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)

$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)

Related

How to move values from 2nd array into the empty places of 1st array

How to move values from 2nd array into the empty places of 1st array
1st array as below
Array
(
[0] => 1
[1] =>
[2] => 4
[3] =>
)
2nd array as below
Array
(
[0] => 5
[1] => 9
)
I want output as merging 2nd array into 1st as shown below
Array
(
[0] => 1
[1] => 5
[2] => 4
[3] => 9
)
I have tried below code.....
for($i=0; $i<$count; $i++){
for($j=$i; $j<=$i; $j++)
if(empty($assign_taskk[$i])){
$assign_taskk[$i] = $taskkk[$i];
}
}
plz help me out for same
Lets say your arrays look like:
$a1 = [
0 => 1,
1 => null,
2 => 4,
3 => null,
];
$a2 = [
0 => null,
1 => 5,
2 => null,
3 => 9,
];
Then you can iterate over first array and add values from the second one when needed:
foreach ($a1 as $k => $v) {
if (empty($v) && !empty($a2[$k])) {
$a1[$k] = $a2[$k];
}
}
Another way to do it using below way-
<?php
$arr1= [1,null,4,null];
$arr2 = [null,5,null,9];
$result = array_values(array_filter($arr1) + array_filter($arr2));
print_r($result)
?>
DEMO: https://3v4l.org/R4aeE
Hi #amod try this
$_newArray = array_values(array_filter($array1) + array_filter($array2));
print_r($_newArray);
You can use below code for this:
$firstArray = [1,'',4,''];
$secondArray = [5,9];
$secondArrayCounter = 0;
foreach($firstArray as $key => $value) {
if (empty($value)) {
$firstArray[$key] = $secondArray[$secondArrayCounter];
$secondArrayCounter++;
}
}
print_r($firstArray);
Hope it helps you.

Simplify Array Duplicate Element in Array PHP

How can we find the count of duplicate elements in a multidimensional array,
I have an array like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 8
)
[3] => Array
(
[btel] => 10
)
)
Question: How to simplify the structure of array, i mean can be counting the value if there is indicate that have same key ?
just like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 18
)
)
So far, i've tried this way, but it didn't help me. My array is store in $test
$test = [sample array]
$count = array();
foreach ($test as $key => $value) {
foreach ($value as $k => $val) {
if (isset($count[$val])) {
++$count[$val];
} else {
$count[$value] = 1;
}
}
}
print_r($count);
<?php
$array = [
"0" => ["brti" => 29],
"1" => ["voda" => 6],
"2" => ["btel" => 8],
"3" => ["btel" => 10],
];
$final = array();
array_walk_recursive($array, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
});
print_r($final);
});
check demo
You can do it in very simple way,
$test = [];
foreach ($array as $value)
{
foreach ($value as $k => $v)
{
// $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
$test[$k] = (empty($test[$k]) ? 0: $test[$k]); // below php 7
$test[$k] += $v;
}
}
print_r($test);
Output:
Array
(
[brti] => 29
[voda] => 6
[btel] => 18
)
Working demo.

How to sum the values of an associative array?

How can I add the array elements by key? Thanks in advance!
Please find the code snippet below
(
[2] => Array
(
[addition_price] => Array
(
[0] => 0
[1] => 40
[2] => 40
)
)
[3] => Array
(
[addition_price] => Array
(
[0] => 100
)
)
)
Desired result:
[2] = 0 + 40 + 40 = 80
[3] = 100
you should try this:
$array = [
0 => [
"addition_price" => [
0,
40,
40
]
],
1 => [
"addition_price" => [
100
]
],
];
foreach ($array as $key=>$value) {
if(!empty($value['addition_price']) && is_array($value['addition_price'])){
echo $key. " => " .array_sum($value['addition_price']). "<br>";
}
}
try this way, i hope it works:
foreach($array as $key => $value){
$sum = 0;
foreach($value['addition_price'] as $v){
$sum += $v;
}
$array[$key] = $sum;
}
Use array_sum for summing up, and array_map to do that for every item in the array
$result = array_map(
function($a) { return array_sum($a['addition_price']); },
$input
);

Merging 3 arrays in PHP

I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);

find duplicate value in multi-dimensional array

From a function I am given a multidimensional array like this:
array(
[0] => array(
[0] => 7,
[1] => 18
),
[1] => array(
[0] => 12,
[1] => 7
),
[2] => array(
[0] => 12,
[1] => 7,
[2] => 13
)
)
I need to find duplicate values in the 3 arrays within the main array. For example, if value 7 repeats in the 3 arrays, return 7.
<?php
$array = array(array(7,18), array(12,7), array(12, 7, 13));
$result = array();
$first = $array[0];
for($i=1; $i<count($array); $i++){
$result = array_intersect ($first, $array[$i]);
$first = $result;
}
print_r($result);//7
?>
use my custom function
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
$arr = array_icount_values($arry);
echo "<pre>";
print_r($arr);
exit;
OUPUT
Array
(
[7] => 3
[18] => 1
[12] => 2
[13] => 1
)
hope this will sure help you.
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
use this code
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
You will need to loop through the first array, and for each value in it, see if it is in_array().
$findme = array();
foreach ($array[0] as $key => $value)
{
if (in_array ($value, $array[1]) && in_array ($value, $array[2]))
{
$findme[] = $value;
}
}
// $findme will be an array containing all values that are present in all three arrays (if any).

Categories