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
);
Related
After flattening a multidimensional array, I have a resulting array, which running print_r() on gives me the following output:
Array
(
[0] => 9999
)
Array
(
[0] => 8888
)
Array
(
[0] => 7777
)
Array
(
[0] => 6666
)
I'm hoping to combine these arrays, so that print_r() would output it like this:
Array
(
[0] => 9999
[1] => 8888
[2] => 7777
[3] => 6666
)
Looking through stackoverflow and other documentation, I've seen suggestions on array_merge, array_merge_recursive, array_combine, implode, and others, but for some reason (maybe because these arrays are all at the same level?), these suggestions haven't worked.
Thanks in advance for any ideas.
Here is a simplified example of how I'm getting this strange output:
$multi_dim_array = array(
array("Details"=>array("Category"=>array("CategoryId" => 15, "CategoryName" => "Misc Products"), "Id" => 1, "Number" => 9999)),
array("Details"=>array("Category"=>array("CategoryId" => 12, "CategoryName" => "Random Products"), "Id" => 2, "Number" => 8888))
);
function array_flatten($array) {
$return = array();
$nums = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$return = array_merge($return, array_flatten($value));
} else {
$return[$key] = $value;
}
}
if(isset($return["Number"])) {
array_push($nums, $return["Number"]);
// echo "<pre>";
// // var_dump($array);
// print_r($nums);
// echo "</pre>";
$output = array_reduce($nums, function($carry, $item) {
$carry[] = $item;
return $carry;
}, []);
echo "<pre>";
print_r($output);
echo "</pre>";
}
return $return;
}
$result = array_flatten($multi_dim_array);
Initial Variable
$arr = [
[ 999999 ],
[ 888888 ],
[ 777777 ],
[ 666666 ]
];
One liner:
$output = array_merge(...$arr);
print_r($output);
With reduce
// This is your format
$output = array_reduce($arr, function($carry, $item) {
$carry[] = $item;
return $carry;
}, []);
print_r($output);
Output
Array
(
[0] => 999999
[1] => 888888
[2] => 777777
[3] => 666666
)
Try this:
$new_array = array_merge(...$old_array);
print_r($new_array);
Also see: https://www.php.net/manual/en/function.array-merge.php
Edit:
Now that I've seen the updated answer, here is my solution:
<?php
$nums = array(
array(
0 => 9999
),
array(
0 => 9999
),
array(
0 => 8888
),
array(
0 => 8888
),
array(
0 => 8888
)
);
$output = array();
for ($i=0; $i < count($nums); $i++) {
$current_subarr = $nums[$i];
array_push($output, $current_subarr[0]);
}
print_r($output);
?>
Outputs:
Array
(
[0] => 9999
[1] => 9999
[2] => 8888
[3] => 8888
[4] => 8888
)
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.
I have array something like this
Array
(
[0] => Array
(
[product_id] => 13
[unit] => 1
[price] => 20.0000
[total] => 20.0000
)
[1] => Array
(
[product_id] => 15
[unit] => 2
[price] => 30.0000
[total] => 10.0000
)
)
I was stuck to transform above array to the "ProductList" in the following pattern
array(
"UserID" => 2,
"ProductList" => [
{
"ProductID"=> 13,
"Price"=> 20.0000
},
{
"ProductID"=> 15,
"Price"=> 30.0000
}
]
)
I tried like this:
$products = [];
foreach($items as $item) {
if(!empty($item['product_id'])) {
$product = '{"ProductID"=>' . $item['product_id'] . '}';
$products[] = $product;
}
}
But not the expected result.
You're looking for json_encode(): http://php.net/manual/en/function.json-encode.php
Assign your array to a variable, for example $products, and then you can simply write json_encode($products) to achieve your desired result.
Try this,
$prodlist = array();
$x = 0;
foreach($arrs as $arr) {
//if ($arr['product_id'] == "" && $arr['price'] == "") continue;
$prodlist[$x]['Price'] = $arr['price'];
$prodlist[$x]['ProductID'] = $arr['product_id'];
$x += 1;
}
$arr2return['user_id'] = $user_id;
$arr2return['ProductList'] = $prodlist;
json_encode($arr2return);
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
)
)
This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 9 months ago.
I have the following array
Array (
[0] => Array
(
[0] => ALFA
[1] => 213
)
[1] => Array
(
[0] => ALFA
[1] => 151
)
[2] => Array
(
[0] => ALFA
[1] => 197
)
[3] => Array
(
[0] => BETA
[1] => 167
)
[4] => Array
(
[0] => ZETA
[1] => 254
)
[5] => Array
(
[0] => GAMA
[1] => 138
)
[6] => Array
(
[0] => GAMA
[1] => 213
)
)
And I would like to group the key[0] of the subarray so I can see how many equal keys it has.
Something like that:
ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2
I tried with array_count_values, but without success.
foreach ($array as $value) {
echo '<pre>';
print_r(array_count_values($value));
echo '</pre>';
}
With that we have following result:
Array
(
[ALFA] => 1
[213] => 1
)
Array
(
[ALFA] => 1
[151] => 1
)
...
Array
(
[GAMA] => 1
[213] => 1
)
And after that I would like to sum the values of each group as well.
ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213
I think that when we solve the first part of the problem, the second would follow easier with quite the same method.
The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:
ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5
This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.
I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.
<?php
$result = array();
foreach ($array as $el) {
if (!array_key_exists($el[0], $result)) {
$result[$el[0]] = array();
}
$result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>
Result:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Solution for you is here:
Code:
$input = [
['alfa', 123],
['alfa', 223],
['alfa', 122],
['alfa', 554],
['alfa', 34],
['dalfa', 123],
['halfa', 223],
['dalfa', 122],
['halfa', 554],
['ralfa', 34]
];
$result = [];
foreach ($input as $node) {
if (isset($result[$node[0]])) {
$result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
} else {
$result[$node[0]] = ['sum' => $node[1], 'count' => 1];
}
}
print_r($result);
foreach ($result as $key => &$data) {
$data = $data['sum'] / $data['count'];
}
print_r($result);
Output:
Array
(
[alfa] => Array
(
[sum] => 1056
[count] => 5
)
[dalfa] => Array
(
[sum] => 245
[count] => 2
)
[halfa] => Array
(
[sum] => 777
[count] => 2
)
[ralfa] => Array
(
[sum] => 34
[count] => 1
)
)
Array
(
[alfa] => 211.2
[dalfa] => 122.5
[halfa] => 388.5
[ralfa] => 34
)
$sort = array();
foreach ($array as $value) {
$sort[$value[0]][] = $value[1];
}
then you count how many keys each has
$keys = array();
foreach($sort as $k => $v) {
$keys[$k] = count($v);
}
then for calculating the amount
$sum = array();
$average = array();
foreach($sort as $k => $v) {
$amount = 0;
foreach($v as $val) {
$amount += $val;
}
$sum[$k] = $amount;
$average[$k] = $amount / $keys[$k];
}
HOWEVER, If you want all the details in one array:
$final = array();
foreach ($array as $value) {
$final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
$final[$k]["amount"] = count($v['values']);
$amount = 0;
foreach($v['values'] as $val) {
$amount += $val;
}
$final[$k]["sum"] = $amount;
$final[$k]["average"] = $amount / $final[$k]["amount"];
}
example: http://jdl-enterprises.co.uk/sof/25789697.php
Includes Output
Just copy the codes to your favorite text editor, sure it works perfectly.
$items = [
['ALFA',213],
['ALFA',151],
['ALFA',197],
['BETA',167],
['ZETA',254],
['GAMA',138],
['GAMA',213]
];
echo '<pre>' . print_r($items,true) . '</pre>';
$result;
foreach ($items as $value) {
# code...
if (isset($result[$value[0]])) {
$sum = $result[$value[0]]['sum'] + $value[1];
$count = $result[$value[0]]['count'] + 1;
$result[$value[0]] = ['sum' => $sum , 'count' => $count, 'divided' => ($sum / $count)];
} else {
$result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
$myArray = [
["ALFA",213],
["ALFA",151],
["ALFA",197],
["BETA",167],
["ZETA",254],
["GAMA",138],
["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
//AVOID PESKY NOTICES FOR UNDEFINED INDEXES
if ( !array_key_exists($val[0],$a1) ) {
$a1[$val[0]] = array("count" => 0,"total" => 0);
$res[$val[0]] = 0;
}
//INCREMENT THE COUNT OF INSTANCES OF THIS KEY
$a1[$val[0]]["count"]++;
//INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
$a1[$val[0]]["total"]+=$val[1];
// UPDATE RESULT ARRAY
$res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}
print_r($res);
Should result in:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Sample: http://phpfiddle.org/lite/code/a7nt-5svf