I have below two arrays with strings and numbers,
I want to keep only one strings header and sum numeric value from each key value with another array.
I have tried many of the solutions available online but nothing found as required.
$array1 =
Array
(
[0] => Array
(
[0] => Out Of Warranty
[1] => Total Orders
[2] => Total Qty
[3] => Canceled Orders
)
[1] => Array
(
[0] => Today<br/>(04-26-2020)
[1] => 1
[2] => 1
[3] => 0
)
[2] => Array
(
[0] => Yesterday<br/>(04-25-2020)
[1] => 0
[2] => 0
[3] => 0
)
[3] => Array
(
[0] => This Week<br/>(04-20-2020 - 04-26-2020)
[1] => 22
[2] => 39
[3] => 0
)
[4] => Array
(
[0] => Last Week<br/>(04-13-2020 - 04-19-2020)
[1] => 7
[2] => 7
[3] => 0
)
[5] => Array
(
[0] => This Month<br/>(04-01-2020 - 04-26-2020)
[1] => 29
[2] => 46
[3] => 0
)
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-26-2020)
[1] => 30
[2] => 47
[3] => 0
)
)
$array2 =
Array
(
[0] => Array
(
[0] => Out Of Warranty
[1] => Total Orders
[2] => Total Qty
[3] => Canceled Orders
)
[1] => Array
(
[0] => Today<br/>(04-24-2020)
[1] => 10
[2] => 10
[3] => 0
)
[2] => Array
(
[0] => Yesterday<br/>(04-23-2020)
[1] => 7
[2] => 7
[3] => 0
)
[3] => Array
(
[0] => This Week<br/>(04-20-2020 - 04-24-2020)
[1] => 51
[2] => 51
[3] => 0
)
[4] => Array
(
[0] => Last Week<br/>(04-13-2020 - 04-19-2020)
[1] => 31
[2] => 31
[3] => 0
)
[5] => Array
(
[0] => This Month<br/>(04-01-2020 - 04-24-2020)
[1] => 93
[2] => 93
[3] => 0
)
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-24-2020)
[1] => 1281
[2] => 1281
[3] => 1
)
)
Expected output as Strings should be use only once and numbers should be added to each other.
For example output should be 6 index i.e sum of 6 index from array1 and array2 -
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-26-2020)
[1] => 1311
[2] => 1328
[3] => 1
)
If your arrays are always sorted in the same order:
$newItems = [];
foreach ($array1 as $key => $item) {
$newItems[] = [
$item[0],
$item[1] + $array2[$key][1],
$item[2] + $array2[$key][2],
$item[3] + $array2[$key][3],
];
}
If keys in arrays are in distinct orders:
$newItems = [];
foreach ($array1 as $item) {
$name = $item[0];
$newItems[$name] = $item;
}
foreach ($array2 as $item) {
$name = $item[0];
$newItems[$name][1] += $item[1];
$newItems[$name][2] += $item[2];
$newItems[$name][3] += $item[3];
}
// apply array_values to get 0-indexed array
$newItems = array_values($newItems);
Only iterate the elements that are necessary for your summing logic. Using 2 loops will be the most concise and deliberate way to sum columns [1], [2], and [3].
You can create a new output array, but merely adding the second array values to the first affords a simpler addition-assignment syntax.
Code: (Demo)
for ($i = 1, $size = count($array2); $i < $size; ++$i) { // don't iterate [0] subarray (headers)
for ($col = 1; $col <= 3; ++$col) { // don't iterate [0] element (name)
$array1[$i][$col] += $array2[$i][$col];
}
}
var_export($array1);
Output:
array (
0 =>
array (
0 => 'Out Of Warranty',
1 => 'Total Orders',
2 => 'Total Qty',
3 => 'Canceled Orders',
),
1 =>
array (
0 => 'Today<br/>(04-26-2020)',
1 => 11,
2 => 11,
3 => 0,
),
2 =>
array (
0 => 'Yesterday<br/>(04-25-2020)',
1 => 7,
2 => 7,
3 => 0,
),
3 =>
array (
0 => 'This Week<br/>(04-20-2020 - 04-26-2020)',
1 => 73,
2 => 90,
3 => 0,
),
4 =>
array (
0 => 'Last Week<br/>(04-13-2020 - 04-19-2020)',
1 => 38,
2 => 38,
3 => 0,
),
5 =>
array (
0 => 'This Month<br/>(04-01-2020 - 04-26-2020)',
1 => 122,
2 => 139,
3 => 0,
),
6 =>
array (
0 => 'This Year<br/>(01-01-2020 - 04-26-2020)',
1 => 1311,
2 => 1328,
3 => 1,
),
)
Related
I would like to switch from array 1 to array 2 according to the model below
I'm stuck on the implementation of item averages
the lessons, the number of notes and the order of the notes are random
Array 1
$tabAsso =
Array
(
[51] => Array
(
[id] => 51
[name] => JOHN
[studies] => Array
(
[0] => math
[1] => LV1
[2] => math
[3] => LV1
[4] => history
[5] => history
)
[notesC] => Array
(
[0] => 12
[1] => 18
[2] => 28
[3] => 45
[4] => 10
[5] => 18
)
[denumsC] => Array
(
[0] => 15
[1] => 60
[2] => 40
[3] => 75
[4] => 12
[5] => 45
)
)
[52] => Array
(
[id] => 52
[name] => PETER
[studies] => Array
(
[0] => sport
[1] => tech
[2] => sport
...
For example for the math average, you must read :
notesC:
sum (12 + 28)
denumC
sum (15 +40)
then average : (40/55) *20 = 14.5
I would like to reach this array 2
[51] => Array
(
[id] => 51
[name] => JOHN
[studies] => Array
(
[0] => math
[1] => LV1
[2] => history
)
[averages] => Array
(
[0] => 14.5
[1] => 9.3
[2] => 9.8
)
)
[52] => Array
(
[id] => 52
[name] => PETER
[studies] => Array
(
[0] => sport
[1] => tech
)
[averages] => Array
(
[0] => xx
[1] => xx
)
)
...
So far I have managed to do this ...
$tabAssoForBar = [];
foreach ($tabAsso as $id => $t) {
foreach ($t['studies'] as $k => $m) {
if (!array_key_exists($id, $tabAssoForBar)) {
$tabAssoForBar[$id] = [
'id' => $id,
'name' => $t['name'],
];
$tabAssoForBar[$id]['studies'] = [$m];
} else {
if (!in_array($m, $tabAssoForBar[$id]['studies'])) {
$tabAssoForBar[$id]['studies'][] = $m;
} else {
// nothing
}
}
}
};
I return studies with only 3 fields (math, LV1, history) but cannot create the averages field
Thanks for your help
You might use an approach to get all the indices from
"study" for a all the unique values, and get the values from "notesC" and "denumsC" for those corresponding indices.
Then per unique value for "study", first sum them separately for "notesC" and "denumsC" and then divide those results and multiply the outcome by 20 to fulfill this formula:
(40/55) *20 = 14.5
You can create the result array by using the current index as the index in the new array and the unique studies and averages to it.
For example
$tabAssoForBar = [];
foreach ($tabAsso as $id => $t) {
$uniqueStudies = array_unique($t['studies']);
$averages = [];
foreach ($uniqueStudies as $uniqueStudy) {
$keysFromStudies = array_keys(array_filter($t['studies'], function($x) use ($uniqueStudy) {
return $x === $uniqueStudy;
}));
$averages[] = round(
(
array_sum(array_intersect_key($t['notesC'], array_flip($keysFromStudies))) /
array_sum(array_intersect_key($t['denumsC'], array_flip($keysFromStudies)))
) * 20,
1
);
}
$tabAssoForBar[$id] = [
'id' => $t['id'],
'name' => $t['name'],
'studies' => array_values($uniqueStudies),
'averages' => $averages
];
}
print_r($tabAssoForBar);
Output
Array
(
[51] => Array
(
[id] => 51
[name] => JOHN
[studies] => Array
(
[0] => math
[1] => LV1
[2] => history
)
[averages] => Array
(
[0] => 14.5
[1] => 9.3
[2] => 9.8
)
)
)
See a php demo
Below is my array:
Array
(
[3] => Array
(
[2] => 3
[4] => 1
[5] => 2
[6] => 2
)
[5] => Array
(
[2] => 1
[3] => 2
[4] => 3
[6] => 3
)
In this array I want to find the maximum number and if the array contains the same maximum values then we choose one maximum value randomly.
Expected output like below:
Array
(
[3] => Array
(
[2] => 3
)
[5] => Array
(
[4] => 3
)
[6] => Array
(
[2] => 3
)
)
This is what I've tried:
$found = Array( [3] => Array ( [2] => 3 [4] => 1 [5] => 2 [6] => 2 ) [5] => Array ( [2] => 1 [3] => 2 [4] => 3 [6] => 3 ) [6] => Array ( [2] => 3 [3] => 2 [4] => 2 [5] => 3 ))
$fmaxnum = array();
foreach($found as $fk => $fv){
$fmaxnum[$fk] = max($fv);
}
echo "<pre>";print_r($fmaxnum);echo "</pre>"
You will get max value with max() but for index you have to use array_keys()
You can try this:
$found = Array ( '3' => Array ( '2' => 3 ,'4' => 1, '5' => 2, '6' => 2 ),
'5' => Array ( '2' => 1 ,'3' => 2, '4' => 3, '6' => 3 ),
'6' => Array ( '2' => 3 ,'3' => 2, '4' => 2, '5' => 3 )
);
$fmaxnum = array();
foreach($found as $fk => $fv){
$max_key = array_keys($fv, max($fv));
$fmaxnum[$fk] = array(
($max_key[0]) => max($fv) /* This will give small index value */
/* (count($max_key)-1) => => max($fv) // this will give highest index value */
);
}
echo "<pre>";
print_r($fmaxnum);
echo "</pre>";
Simple solution with array_map and array_keys functions:
// supposing $arr is your initial array
$arrMax = array_map(function($v){
$maximum = max($v);
return [array_keys($v, $maximum)[0] => $maximum];
}, $arr);
print_r($arrMax);
The output:
Array
(
[3] => Array
(
[2] => 3
)
[5] => Array
(
[4] => 3
)
[6] => Array
(
[2] => 3
)
)
if you just want to know the highest value as I understood
In this array I want to find the maximum number and if the array
contains the same maximum values then we choose one maximum value
randomly.
you could just do this
$array = [['3','1','2','2'],['1','2','3','3'],['2','1','1','3']];
$result = [];
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
$result[] = $value;
}
echo max($result);
this will foreach all the array and push the values on $result, then you just have one level array and easily use max function
This question already has answers here:
PHP Array Group by one field and Sum up two fields [duplicate]
(2 answers)
Closed 4 months ago.
My situation is similar to this thread :
Associative array, sum values of the same key
However in my case all keys are number.
I would like to reduce / combine array where key 0 is similar and make a sum of all other keys.
Here is my original array :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 13
[4] => 0
)
[2] => Array
(
[0] => 222032
[1] => 0
[2] => 0
[4] => 15
)
[3] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
[4] => Array
(
[0] => 222032
[1] => 0
[2] => 7
[4] => 0
)
)
and here is the output i need :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[4] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
)
The solution of other thread is not working because they use the key name and i don't know how i can adapt this to my situation.
Please if you can give me an example of working solution.
REPLY :
For now i try something like that : Take from other thread
$sum = array_reduce($data, function ($a, $b) {
if (isset($a[$b[0]])) {
$a[$b[0]]['budget'] += $b['budget'];
}
else {
$a[$b[0]] = $b;
}
return $a;
});
But this example look is only for key named budget but in my case is number and i have 3 key [1] [2] [3] how can't sum key 1,2,4 where key 0 is similar
This should work for you:
Basically I just loop through your array and check if there is already an element in $result with the key of the first element of $v. If not I initialize it with an array_pad()'ed array of 0's + the current array of the iteration of the foreach loop.
And after this I loop through each element of $v expect the first one and add it to the result array.
At the end I just reindex the result array with array_values().
<?php
foreach($arr as $v){
if(!isset($result[$v[0]]))
$result[$v[0]] = array_pad([$v[0]], count($v), 0);
$count = count($v);
for($i = 1; $i < $count; $i++)
$result[$v[0]][$i] += $v[$i];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[3] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[3] => 0
)
)
try this
$data = Array
(
0 => Array
(
0 => 93042,
1 => 3,
2 => 0,
4 => 0,
),
1 => Array
(
0 => 222032,
1 => 0,
2 => 13,
4 => 0,
),
2 => Array
(
0 => 222032,
1 => 0,
2 => 0,
4 => 15,
),
3 => Array
(
0 => 152963,
1 => 45,
2 => 0,
4 => 0,
),
4 => Array
(
0 => 222032,
1 => 0,
2 => 7,
4 => 0,
),
);
var_dump($data);
// grouping
$tab1 = array();
foreach ($data as $e) {
if (!isset($tab1[$e[0]])) {
$tab1[$e[0]] = array();
}
$tab1[$e[0]][] = $e;
}
//var_dump($tab1);
// summing
$tabSum = array();
foreach ($tab1 as $id => $t) {
foreach ($t as $e) {
unset($e[0]);
if (!isset($tabSum[$id])) {
$tabSum[$id] = $e;
} else {
foreach ($e as $key => $value) {
$tabSum[$id][$key] += $value;
}
}
}
}
var_dump($tabSum);
I need to sum up some values from subarrays in an array.
I have this array
Array
(
[smecid_2] => Array
(
[0] => 1
[1] => SMEC 55.6
[2] => 960
[3] => 864
[4] => 960
[5] => 864
)
[smecid_6] => Array
(
[0] => 3
[1] => SMEC 55.6 ATEX EX
[2] => 1290
[3] => 1161
[4] => 3870
[5] => 3483
)
)
What I want to do is sum up all fields from key [4] of each subarray and be able to echo the total in $total;
In this example $total; would be 4830 (960+3870).
Also, the array could hold more subarrays then these 2, when a user submits more products to order.
<?php
$array = array
(
'smecid_2' => array
(
0 => 1,
1 => 'SMEC 55.6',
2 => 960,
3 => 864,
4 => 960,
5 => 864,
),
'smecid_6' => array
(
0 => 3,
1 => 'SMEC 55.6 ATEX EX',
2 => 1290,
3 => 1161,
4 => 3870,
5 => 3483,
)
);
$sum = 0;
foreach ($array as $subarray)
{
$sum += $subarray[4];
}
echo $sum;
See it in action
I have an array of all possible combinations of values, a bit like working out what monetary values I could make with only certain coins. Now I have an array built but much of the useful data are keys and not values.
A small snippet is below:
Each root key is an array with keys total, denomination and quantity. Each of the quantities multiplied by the denominations total the total. While I've been able to access the total easily enough I just can't get a handle on the denominations and the quantities.
It's my plan to output to separate radio buttons like so:
foreach($array as $arr)
{
echo '<input type="radio" name="name" value="'.$arr[$total].'">';
foreach($arr[denom] as $index => $d)
{
echo $d[qty][$index].' x '.$d[denom][$index].' = '.($qty[$index]*$denom[$index]).'<br>';
}
}
Here's the array I have, any help would be much appreciate, I'm usually great at this bot it's driving me crazy
Array
(
[2] => Array
(
[total] => 105
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 1
)
)
[3] => Array
(
[total] => 210
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 2
)
)
[4] => Array
(
[total] => 300
[denom] => Array
(
[0] => 300
)
[qty] => Array
(
[0] => 1
)
)
[5] => Array
(
[total] => 405
[denom] => Array
(
[0] => 300
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
[6] => Array
(
[total] => 500
[denom] => Array
(
[0] => 500
)
[qty] => Array
(
[0] => 1
)
)
[7] => Array
(
[total] => 605
[denom] => Array
(
[0] => 500
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
Constant non-numeric array indices should be written like any other string, i.e. encapsulated in quotes.
foreach($array as $arr) {
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d){
for ($j = 0;$j < count($denom);$j++) {
echo $d['qty'][$j].' x '.$d['denom'][$j].' = ';
echo ($d['qty'][$j]*$d['denom'][$j]) . '<br>';
}
}
}
First format your array like this in my code, add 6, 7 array elements. I modify for loop too.
<?php
$array = array(2 => array('total' => 105, 'denom' => array(0 => 105), 'qty' => array(0 => 1)),
3 => array('total' => 210, 'denom' => array(0 => 105), 'qty' => array(0 => 2)),
4 => array('total' => 300, 'denom' => array(0 => 300), 'qty' => array(0 => 1)),
5 => array('total' => 405, 'denom' => array(0 => 300, 1 => 105), 'qty' => array(0 => 1, 1 => 1)),
);
foreach($array as $arr)
{
//var_dump($arr);
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d)
{
echo $arr['qty'][$index].' x '.$d.' = '.($arr['qty'][$index]*$d).'<br>';
}
}
?>