I have these two arrays result in print_r:
Array ( [0] => multidesign1 [1] => multidesign1 [2] => multidesign2 [3] => multidesign2 )
Array ( [0] => 30 [1] => 7 [2] => 40 [3] => 1 )
The actual contents should be:
multidesign1 has 30 and 7 so its 37 while multidesign2 has 40 and 1 so its 41.
Can I combine these two arrays so I could come up with multidesign1=>37 and multidesign2=>41 ?
Thanks.
$newArray = array();
foreach(range(0, count($firstArray) - 1) as $index) {
if(isset($newArray[$index])) {
$newArray[$index] += $secondArray[$index];
} else {
$newArray[$index] = $secondArray[$index];
}
}
Is that something like what you're looking for?
$result = array();
foreach ($array1 as $i => $key) {
$result[$key] += $array2[$i];
}
Related
I have two arrays with same amount of values. I need to combine them ( array1 value to key, array2 value as value) without losing the values of the second array due to duplicate key. when I use combine_array() as expected it just gets the last value of the second array with the same key.
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Desired result
Array
(
[1] => 1
[2] => Array(
[0]=>2
[1]=>3
)
[3] => 2
)
This code will meet your request
$array1 = array("0"=>1,"1"=>2,"2"=>2,"3"=>3);
$array2 = array("0"=>1,"1"=>2,"2"=>3,"3"=>4);
$array = array();
foreach($array1 as $key => $value){
if($value != $array2[$key]){
$array[$key][] = $value;
$array[$key][] = $array2[$key];
}else{
$array[$key] = $value;
}
}
print_r($array);
The desired result is
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
)
)
I'm sure there are way better solutions than this, but it does the job for now. I would appreciate if someone can send a better written solution.
$combined = array();
$tempAr = array();
$firstMatch = array();
$count = 0;
foreach ($array1 as $index => $key) {
if (array_key_exists($key, $combined)) {
$tempAr[] = $array2[$index];
$count++;
} else {
$totalCount = $count;
}
if (!array_key_exists($key, $firstMatch)) {
$firstMatch[$key] = $array2[$index];
}
$output = array_slice($tempAr, $totalCount);
$combined[$key] = $output;
}
$combined = array_merge_recursive($firstMatch, $combined);
I am trying to split array data into multiple arrays based on change in data value at known position (column).
$input = array(
array(1,2,3),
array(4,5,3),
array(7,8,4),
array(9,10,4),
array(11,12,4)
);
Here column 3 changes values from 3 to 4
and expected result is to have 2 arrays
$out1 = array(array(1,2,3),array(4,5,3));
$out2 = array(array(7,8,4), array(9,10,4), array(11,12,4));
since number of rows are variable, cannot use array_chunk
since column 3 values are variable, cannot use array_filter
number of output arrays are also variable.
trying splice but failing...
You can use array_reduce to make new array, where index will be equal to last numbers in items
$new = array_reduce($input, function($c, $x) { $c[$x[2]][] = $x; return $c; }, [] );
$out1 = $new[3];
$out2 = $new[4];
demo
But if array is not sorted and you want to split at points of changing that number, the code can be
$i = -1;
$last = null;
$new = [];
foreach($input as $x) {
if ($x[2] != $last) {
$i++;
$last = $x[2];
}
$new[$i][] = $x;
}
demo
You can use split index with index of array,
$out1 = $out2 = [];
$splitIndex = 2;
foreach($input as $k => $v){
if($k < $splitIndex){
$out1[] = $v;
}else{
$out2[] = $v;
}
}
print_r($out1);
print_r($out2);
Working demo
Output:-
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 3
)
)
Array
(
[0] => Array
(
[0] => 7
[1] => 8
[2] => 4
)
[1] => Array
(
[0] => 9
[1] => 10
[2] => 4
)
[2] => Array
(
[0] => 11
[1] => 12
[2] => 4
)
)
I am trying to find a way to allow me to count the number of times a value appears across multiple arrays as well as, for each unique value, the total count.
The data looks like the below:
Array ( [id] => 4383 [score] => 3 )
Array ( [id] => 4382 [score] => 4 )
Array ( [id] => 4381 [score] => 5 )
Array ( [id] => 4383 [score] => 7 )
Array ( [id] => 4383 [score] => 1 )
Array ( [id] => 4382 [score] => 2 )
Array ( [id] => 4381 [score] => 8 )
The above should return:
4383 - 3 - 11
4382 - 2 - 6
4381 - 2 - 13
I have used array_push and created one array called $output and looped using foreach to get a count of the id's using:
foreach($output as $row) {
$array[$row[0]]++;
}
This returns the correct count of id but I cannot get the total score for each id - I have tried:
foreach($output as $row) {
foreach($row as $r) {
$array[$row[0]]=$array[$row[1]]+$array[$r[1]];
}
}
but it returns zero for everything
Like below:
$result = array();
foreach ($data as $value) {
if (!isset($result[$value['id']])) {
$result[$value['id']] = array('count' => 0, 'sum' => 0);
}
$result[$value['id']]['count'] += 1;
$result[$value['id']]['sum'] += $value['score'];
}
$result = array();
foreach ($output as $row) {
if (!array_key_exists($row[0], $result)) {
$result[$row[0]] = array("Count" => 1, "Total" => $row[1]);
}
else {
$result[$row[0]]['Count'] += 1;
$result[$row[0]]['Total'] += $row[1];
}
}
print_r($result);
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
Easy question, I filled my array the following way:
$options = range(1, 10);
This will result:
array
(
[0] => 1
[1] => 2
etc. etc.
)
This is not the result I want..
I need my array like this:
array
(
[1] => 1
[2] => 2
etc.
)
How to accomplish this easy task?
Maybe like this:
$options = range(0, 10);
unset($options[0]);
working example
<?php
for( $i = 1; $i <= 10; $i ++ ) {
$array[$i] = $i;
}
Voila. :)
if you want a one-liner instead of a for-loop like Berry suggested, just use array_combine:
$array = array_combine(range(1,10),range(1,10));
function myRange($start, $limit, $step)
{
$myArr = array();
foreach((array) range($start, $limit,$step) as $k => $v)
{
$myArr[$k+1] = $v;
}
return $myArr;
}
print_r(myRange(0, 100, 10));
?>
Result
------
Array
(
[1] => 0
[2] => 10
[3] => 20
[4] => 30
[5] => 40
[6] => 50
[7] => 60
[8] => 70
[9] => 80
[10] => 90
[11] => 100
)
Or just shift the array
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;