How do I sum subarray elements and group by subarray value? [duplicate] - php

This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 9 months ago.
I want to sum subarray values and group by a subarray value but I am getting error: 'Undefined index: EEReg'.
The array is as follows.
and the current code is;
$total_balances = array();
foreach ($balances as $balance) {
foreach ($balance as $key => $value) {
if ($key == 'MemberNumber' || $key == 'Portfolio') {
continue;
} else {
$total_balances[$balance['Portfolio']][$key] += $value;
}
}
}
I expect the result to be;
$total_balances = [
"Aggressive" => [
"EEReg" => "Sum of EEReg where Portfolio is Aggressive",
"ERReg" => "Sum of ERReg where Portfolio is Aggressive",
],
"Moderate" => [
"EEReg" => "Sum of EEReg where Portfolio is Moderate",
"ERReg" => "Sum of ERReg where Portfolio is Moderate",
]
]

You need to use foreach only once and also you need to define the keys in $total_balance array before using them. Please see below code
$total_balances = array();
foreach ($balances as $balance) {
if( !isset( $total_balances[$balance['Portfolio']] )) {
$total_balances[$balance['Portfolio']] = array('EEREG' => 0, 'ERREG' => 0);
}
$total_balances[$balance['Portfolio']]['EEREG'] += $balance['EEREG'];
$total_balances[$balance['Portfolio']]['ERREG'] += $balance['ERREG'];
}

Related

Compare parameters of multidimentional arrays and merge them

I have 2 multidimensional arrays ($sorted, $sorted_Rcv), with the parameters Account, Analyzed, Received, Year and Month. Received and Analyzed are in different arrays as you can see in the following picture.
What I'm trying to achieve, is to compare the 2 arrays and if Account, Month and Year are identical, merge them, so that in one object I get Account, Received, Analyzed, Month and Year.
This is my current approach. Where I get the following error: Trying to access array offset on value of type int on the if function.
$merged_result = array();
foreach ($sorted as $sorted) {
foreach ($sorted as $value1) {
foreach ($sorted_Rcv as $sorted_Rcv) {
foreach ($sorted_Rcv as $value2) {
if ($value1['Month'] == $value2['Month'] && $value1['Year'] == $value2['Year']) {
$merged_result[]= ['Account' => $value1['Account'], 'Received' => $value2['Received'],'Analyzed' => $value1['Analyzed'],'Month' => $value1['Month'],'Year' => $value1['Year']];
}
}
}
}
}
Any kind of help is much appreciated!
Try to use next foreach loop:
$merged_result = array();
foreach($sorted as $subar1){
foreach($subar1 as $val){
foreach($sorted_Rcv as $subar2){
foreach($subar2 as $val2){
if ($val['Year'] == $val2['Year'] && $val['Month'] == $val2['Month'] && $val['Account'] == $val2['Account']){
$merged_result[] = [
'Year' => $val2['Year'],
'Month' => $val2['Month'],
'Account' => $val2['Account'],
'Analyzed' => $val['Analyzed'],
'Received' => $val2['Received'],
];
}
}
}
}
}
Demo

push first few elements of an array into 2d array

Edit :
i Want a structure like this
'categories' => [
[
'name' => "science" ,
'questions' => [
[
'question' => 'C1_Q2',
'answer' => 'C1_A2',
],
[
'question' => 'C1_Q3',
'answer' => 'C1_A3',
]
]
]
but with help of loop
I am trying to create a questionnaire in which 3 steps need to be done
Create 3 arrays
1.categories - 2d -- like category["science"]["questions"]
2.questions
3.answers
step 1. add 10 questions in question array and add 10 answers in answer arrays
step 2.first 5 question of question array should be inserted to categories["science"]["questions"] and 5 answers to categories["science"]
["answers"]
I created Question and answer array and added 10 , 10 elements in it . but didnt succeed to add its elements as per step2 . I tried few logic
$Category=array();
$Q=array();
$A=array();
for($i=1;$i<=10;$i++)
{
$Q[] = "Question post".$i;
$A[] = "Answer post".$i;
//if($i==5)
//{
// array_push($Category,$Q[i]);
// break;
//} ---logic not working
}
//array first 5 Questions to category array
/*
for($i=1;$i<=5;$i++)
{
//$Category[]=$Q[i];
array_push($Category,$Q[i]);
}
*/ -- not working
print_r($Category);
Any suggestion or help would be appreciated
Try this:
$questions = [];
$answers = [];
for($i=1; $i <= 10; $i++) {
$questions[] = 'Question post' . $i;
$answers[] = 'Answer post' . $i;
}
$categories = ['science', 'something', 'else'];
$result = [];
foreach ($questions as $index => $question) {
if ($index % 5 != 0 || $index == 0) {
$category = current($categories);
} else {
$category = next($categories);
}
$result[$category][] = ['question' => $question, 'answer' => $answers[$index]];
}
var_dump($result);

PHP - Delete element from multidimensional-array based on value [duplicate]

This question already has answers here:
Delete element from multidimensional-array based on value
(7 answers)
Closed 5 years ago.
foreach ($array_leave_dates as $emp => $leave_type) {
foreach ($leave_type as $leave_dates) {
if($leave_type == 'Maternity Leave'){
unset($array_leave_dates[$leave_type]);
}
else{
echo $leave_dates[$row];
}
}
}
Here we can fetch $leave_dates and want to remove or unset leave_type == 'Maternity Leave'. But could'nt. Please help to point out the mistake in my code above.
Have a look at the // comments
foreach ($array_leave_dates as $emp => $leave_type) {
// you treat $leave_type as array here
foreach ($leave_type as $leave_dates) {
// you treat $leave_type as string here
// doesn't feel right
if($leave_type == 'Maternity Leave') {
// you are unsetting with a value
//unset($array_leave_dates[ --> $leave_type <-- ]);
// i assume you want to delete the key
unset($array_leave_dates[$emp]);
}
else{
// $row doesn't seem to exist, looks wrong from here
echo $leave_dates[$row];
}
}
}
Not sure what your data source looks like:
<?php
// Remove the whole employee
$employees = array(
'emp1' => array('sick' => 'Mon - Tue'),
'emp2' => array('bun in oven' => '2016 - 2017'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp]);
}
}
}
print_r($employees);
// OR remove only 'Maternity' from the employee but keep everything else
<?php
$employees = array(
'emp1' => array('sick' => 'Mon - Tue', 'its friday and im not coming in' => 'Fri'),
'emp2' => array('bun in oven' => '2016 - 2017', 'sick' => 'Thu'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp][$leaveName]);
}
}
}
print_r($employees);
If $leave_type can be "Maternity Leave", then why do you search for $leave_dates inside that string value? The question is naturally rethorical. From the very fact that you have two foreach cycles and the second is embedded into the first makes me think that $leave_type is not what you think it is. So, I think you have a multi dimensional array, where the outer keys are employee names or ids and the inner keys are the types. Example:
array(
'John Doe' => array('Sickness' => array('a', 'b', 'c')),
'Mary Doe' => array('Sickness' => array('a', 'b', 'c'), 'Maternal Leave' => array('d', 'e'))
)
If that is the case, then you need to modify your cycles:
foreach ($array_leave_dates as $emp => $leave) {
if ($leave['Maternity Leave']) {
unset($array_leave_dates[$emp]['Maternity Leave']);
}
}
If you want a more general solution, then this might help you:
function removeByKey(&$arr, $k) {
if (arr[$k] !== null) {
unset arr[$k];
}
foreach($arr as $key => $value) {
if (is_array($value)) {
$arr[$key] = removeByKey($arr[$key], $k);
}
}
return $arr;
}

Check if value exist or exclude repeated values array [duplicate]

This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 8 years ago.
This the array...
$rt = array(
'0' => array(
'nombre'=>'Jojo',
'fecah'=> '195',
'fch'=>'12'
),
'1' => array(
'nombre'=>'Tito',
'fecah'=> '197',
'fch'=>'13'
),
'2' => array(
'nombre'=>'Jojo',
'fecah'=> '195',
'fch'=>'12'
),
'3' => array(
'nombre'=>'Joji',
'fecah'=> '195',
'fch'=>'12'
),
);
and this is my code:
$a = array();
foreach ($rt as $k=>$v) {
if (in_array($v['nombre'], $a) && in_array($v['fecah'], $a) && in_array($v['fch'], $a) ) {
$a[]=$k;
echo 'The name ' . $v['nombre'] .' is in the array<br>';
} else {
echo 'The name is not in the array <br>';
}
}
so as you can see in the array index [2] the information also exist in the index [0], so I don't need it again, so I need a away to see if the data get repeated or not... if the data is "unique" then build the new array with the "unique" data if the data already exist then jump to next, but I need to compare the 3 keys not just the name... so how do I do that?
You insert array when it is in_array and you use AND
you should reverse your codes like this
$a = array();
foreach ($rt as $k=>$v) {
if (!in_array($v['nombre'], $a) || !in_array($v['fecah'], $a) || !in_array($v['fch'], $a) ) {
$a[]=$k;
echo 'The name ' . $v['nombre'] .' is in the array<br>';
} else {
echo 'The name is not in the array <br>';
}
}
This is you need this
$newarray = array();
foreach($rt as $key => $value)
{
$nombre = $value['nombre'];
if(!isset($newarray[$nombre]))
{
$newarray[$nombre] = $value;
}
}

PHP sort array of arrays [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I have an array of arrays in PHP that I created like the following:
$wp_players = array();
while ($wp_player = mysql_fetch_array($wp_player_query))
{
$wp_player_ranking = mysql_query(get_ranking_sql($wp_player['id'])) or die(mysql_error());
$wp_ranking = mysql_fetch_array($wp_player_ranking);
array_push($wp_players, array('first_name' => $wp_player['first_name'],
'last_name' => $wp_player['last_name'],
'school_name' => $wp_player['school_name'],
'1st' => $wp_ranking['1st'],
'2nd' => $wp_ranking['2nd'],
'3rd' => $wp_ranking['3rd'],
'4th' => $wp_ranking['4th'],
'5th' => $wp_ranking['5th'],
'total' => ($wp_ranking['1st'] + $wp_ranking['2nd'] + $wp_ranking['3rd'] + $wp_ranking['4th'] + $wp_ranking['5th'])));
}
What I want to do now is have $wp_players array sorted by the 'total' key that's inside each of its elements. Since the Array is not flat, and is an array of arrays, what's the best way to do this in PHP?
array_multisort() will accomplish precisely what you're looking to achieve:
$totals = array();
foreach ($wp_players as $key => $row) {
$totals[$key] = $row['total'];
}
array_multisort($totals, SORT_DESC, $wp_players);
This function will be what you want, this function if from my development framework, It suits for many situations, has order control and reserveKey control parameters.
<?php
function sortByField($arr, $fieldName, $flag = 'desc', $reserveKey = true)
{
$indexArr = array();
foreach ($arr as $idx => $item)
{
$indexArr[$idx] = $item[$fieldName];
}
if ('desc' == $flag)
{
arsort($indexArr);
}
else
{
asort($indexArr);
}
$result = array();
foreach ($indexArr as $idx => $field)
{
if($reserveKey)
{
$result[$idx] = $arr[$idx];
}
else
{
$result[] = $arr[$idx];
}
}
return $result;
}
usage
$wp_players = sortByField($wp_players, 'total');

Categories