Sum the value of single array based on key value - php

This question is not a duplicate of other. it is different,This is current code, I am trying to sum the values of a array based on the same key value of date.
foreach ($TablesArr as $tr) {
$criteria = new CDbCriteria;
$criteria->select = 'date,mal';
$Arr1 = $tr::model()->findAll($criteria);
$array_1 = array();
foreach ($Arr1 as $a1) {
$array_1['date'] = $a1['date'];
$array_1['mal'] = $a1['mal'];
}
}
My Current output is:
Array
(
[date] => 2015-11-00
[mal] => 35
)
Array
(
[date] => 2015-12-00
[mal] => 20
)
Array
(
[date] => 2016-01-00
[mal] => 30
)
Array
(
[date] => 2016-01-00
[mal] => 10
)
Array
(
[date] => 2015-11-00
[mal] => 50
)
If the date is same, then sum the value of mal in the array. For example, In the above array, the date 2015-11-00 appears twice or more than twice (5 or 10 times etc) then sum all of the values of it for that date. Currently it appears twice so for 2015-11-00 the mal values will be 35+50=85. I want my output to be like this below:
Array
(
[date] => 2015-11-00
[mal] => 85
)
Array
(
[date] => 2015-12-00
[mal] => 20
)
Array
(
[date] => 2016-01-00
[mal] => 40
)
I have tried:
$result = array();
foreach($Arr1 as $data) {
$result[ $data['date'] ] += $data['mal'];
}

Your $array_1 variable doesn't contain all the values from the original $Arr1 array. You're overwriting the same elements each time through the loop, so it just contains the last item from $Arr1. These lines:
$array_1['date'] = $a1['date'];
$array_1['mal'] = $a1['mal'];
should be:
$array_1[] = array('date' => $a1['date'], 'mal' => $a1['mal']);
Another problem is that you're resetting $array_1 each time through the outer loop.
You can also use array_merge to combine the arrays, instead of the loop:
$array_1 = array();
foreach ($TablesArr as $tr) {
$criteria = new CDbCriteria;
$criteria->select = 'date,mal';
$Arr1 = $tr::model()->findAll($criteria);
$array_1 = array_merge($array_1, $Arr1);
}
You can use one of the solutions in php group by SUM using multi dimensional array to create an associative array with the sums grouped by date. You can turn this into a 2-dimensional array with another loop:
$newresult = array();
foreach ($result as $date => $mal) {
$newresult[] = array('date' => $date, 'mal' => $mal);
}
DEMO

Related

Count how many times a value appears in this array?

I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.
array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));
Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}
You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);

Unique values of a multidimensional array while inside a foreach loop

I am working within a foreach loop and PARTS my code looks like this:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
The Output result of the above is this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
Yes I see there are similar questions to this. But none of their answers seem to work for me. I'm thinking it might be because I am working inside an foreach loop. Either way, I was wondering if there was a way to get my output above to look like this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
All the duplicates gone, without loosing the formatting of this array. Code I have tried.. but "maybe" wrong was:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
EDIT for Sharanya Dutta:
I have alot of other code, but basically this is where Im trying to use it.
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
Use an array ($arr in the following code) to store the values and print_r only those values which are different from the already stored values:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
DEMO
You may even use $diff after the last line in the foreach loop:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}
DEMO
As you iterate the result set rows and explode the text string, filter the individual values in the current row against all values in all previously encountered rows.
If there are any individual values encountered for the first time, then save the unique values of that row as a new row in the result array.
Code: (Demo)
$resultSet = [
['text' => 'Charcoal,Natural Gas,Combo'],
['text' => 'Charcoal,Propane,Combo'],
['text' => 'Charcoal,Propane,Natural Gas,Combo'],
['text' => 'coal'],
['text' => 'Natural Gas,wood'],
];
$result = [];
foreach ($resultSet as $row) {
$clean = array_diff(
explode(',', $row['text']),
...$result
);
if ($clean) {
$result[] = array_values($clean);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'Charcoal',
1 => 'Natural Gas',
2 => 'Combo',
),
1 =>
array (
0 => 'Propane',
),
2 =>
array (
0 => 'coal',
),
3 =>
array (
0 => 'wood',
),
)

PHP: Merging arrays with the same title

I have some php arrays from a loop, all of them bearing the same name. Now I want to merge them, but it seems not to work...
Here's my loop:
while($row = mysql_fetch_row($sql1)){
$startzeit=strtotime($row[2]);
$endzeit=strtotime($row[3]);
$startzeit_format = date("Y-m-d",$startzeit);
$endzeit_format = date("Y-m-d",$endzeit);
$datearray[] = createDateRangeArray($startzeit_format,$endzeit_format);
}
This should be the merging code:
for($i = 0; $i<count($datearray); $i++)
{
$datesarray = array_merge($datearray[$i]);
}
Anyway, the manual merge works fine:
$datesarray = array_merge( $datearray[0], $datearray[1], $datearray[2], $datearray[3]);
This one leads to the desired output. However I'd like to automatize it, as the single arrays come from a database and I won't add a $datearray[4], $datearray[5] and so on, everytime there is a new entry in the mySQL..
The result of print_r($datearray):
Array (
[0] => Array ( [0] => 2014-03-08 )
[1] => Array ( [0] => 2013-09-15 )
[2] => Array ( [0] => 2013-09-21 )
[3] => Array ( [0] => 2013-10-03
[1] => 2013-10-04
[2] => 2013-10-05
[3] => 2013-10-06 )
)
What you might be looking for is to flatten the array:
$datesarray = call_user_func_array('array_merge', $datearray);
It's identical to how you were manually merging together the array items.
See also: call_user_func_array()
You could also do this inside the loop with a simple loop:
$datesarray = array();
while ($row = mysql_fetch_row($sql1)) {
// ...
foreach (createDateRangeArray($startzeit_format,$endzeit_format) as $item) {
$datesarray[] = $item;
}
}
You are merging a single array to nothing.
$newArray = array_merge($array, $array)
Merges those two arrays but you are doing
$array = array_merge($datearray[$i]);
In affect, you are creating an array from one key of an array.

if we have 5 different array how to merge them in single array in php

I have 5 different array whose structure is :-
Array ( [0] => http://www.php.net/200
)
Array ( [0] => http://www.php.net/?setbeta=1&beta=1302
)
Array ( [0] => http://www.php.net/downloads.php200
)
Array ( [0] => http://www.php.net/docs.php200
)
Array ( [0] => http://www.php.net/FAQ.php302
)
I need to merge these all in a single array whose structure would be like:-
Array ( [0] => http://www.php.net/200
[1] => http://www.php.net/?setbeta=1&beta=1302
[2] => http://www.php.net/downloads.php200
[3] => http://www.php.net/docs.php200
[4] => http://www.php.net/FAQ.php302
)
One thing i want to confirm that these arrays are forming inside a loop function and it could be of any number and also they have a single name i.e $array
Simplest is probably just array_merge().
$merged = array_merge( $ar1, $ar2, $ar3, $ar4, $ar5 );
Use array_merge.
$arr = array_merge($arr1,$arr2,$arr3,$arr4,$arr5);
Edit After seeing your comment, you are having multidimensional array.
$arr = array();
for($i = 0; $i < $old_arr; $i++) {
$arr[] = $old_arr[$i][0];
}
Use array_merge
$arr1=Array ( 0 => 'http://www.php.net/200');
$arr2=Array( 0 => 'http://www.php.net/?setbeta=1&beta=1302');
$arr3=Array( 0 => 'http://www.php.net/downloads.php200');
$merged=array_merge($arr1,$arr2,$arr3);
print_r($merged);
$newarray = array();
while ( is_array( array_get_function_here() ) )
{
$newarray = array_merge( $newarray, $array );
}
I would try that if you get the different arrays in a looping function.
The above $array is something that array_get_function_here() should return for the while loop validity check (if it returns and array, the while check runs as true). array_get_function_here() is just an example and should be some function that returns a value for $array.

How to split a multidimensional array in PHP?

How can I take a multi-dimensional array like the below, and split it into multiple separate arrays? Additional challenge: Although I know there are two pairs in the example below (pageviews, visits), how can you do it assuming that you don't know the number of pairs in the array? For example, I may want to add "time on page" or "pages visited", and could therefore have any number of pairs.
My goal, in the end, would be to have an array like: "26, 9, 18" and another array "20, 4, 9".
I've got an array like this:
Array
(
[20090817] => Array
(
[ga:pageviews] => 26
[ga:visits] => 20
)
[20090818] => Array
(
[ga:pageviews] => 9
[ga:visits] => 4
)
[20090819] => Array
(
[ga:pageviews] => 18
[ga:visits] => 9
)
)
I would have thought the below code would work, but it doesn't get the specific value that I want, and for some weird reason, it trims each value to one character:
$pageViews = array();
$visits[] = array();
foreach ($google_lastMonth as $value) {
foreach ($value as $nested_key => $nested_value) {
$pageViews[] = $nested_value["ga:pageviews"];
$visits[] = $nested_value["ga:visits"];
}
}
Your array is not as deep as you think:
$pageViews = array();
$visits = array();
foreach ($google_lastMonth as $value) {
$pageViews[] = $value["ga:pageviews"];
$visits[] = $value["ga:visits"];
}
I think
you should erase the braket on visit
Ok my bad should be that
$pageViews = array();
$visits = array();
foreach ($result as $value) {
$pageViews[] = $value['ga:pageviews'];
$visits[] = $value['ga:visits'];
}

Categories