I have a problem with my sum of arrays. So I have this array :
Array
(
[0] => Array
(
[totalGames] => 21
[nature] => 542
)
[1] => Array
(
[totalGames] => 2
[nature] => 418
)
[2] => Array
(
[totalGames] => 26
[nature] => 728
)
[3] => Array
(
[totalGames] => 3
[nature] => 542
)
[4] => Array
(
[totalGames] => 2
[nature] => 418
)
)
I want to make a sum of this array to get this result :
Array
(
[0] => Array
(
[totalGames] => 24
[nature] => 542
)
[1] => Array
(
[totalGames] => 4
[nature] => 418
)
[2] => Array
(
[totalGames] => 26
[nature] => 728
)
)
I tried like this :
while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC))
{
if($aData['nature'] == $aRecord['nature']){
$aData[] = $aRecord;
}else{
$aData['nature'] = $aRecord['nature'];
$aData['totalGames'] += $aRecord['nature']['totalGames'];
}
}
But not work. What I'm doing wrong ? Can you help me please ? Thx in advance and sorry for my english.
I also tried but it did not work :
SELECT COUNT(*) as totalGames, nature FROM master WHERE date(date)="2015-11-20" GROUP BY nature ORDER by totalGames
Your code should be:
$myArr = array(array('totalGames' => 21, 'nature' => 542),array('totalGames' => 2,'nature' => 418),array('totalGames' => 26,'nature' => 728), array('totalGames' => 3,'nature' => 542),array('totalGames' => 2,'nature' => 418));
$sum = array_reduce($myArr, function ($a, $b) {
isset($a[$b['nature']]) ? $a[$b['nature']]['totalGames'] += $b['totalGames'] : $a[$b['nature']] = $b;
return $a;
});
print_r($sum);
Try as
while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
$hash = $aRecord['nature'];
if(isset($aData[$hash])){
$aData[$hash]['totalGames'] += $aRecord['totalGames'];
}else{
$aData[$hash]['nature'] = $aRecord['nature'];
$aData[$hash]['totalGames'] = $aRecord['totalGames'];
}
}
Related
I have a PHP array with the following data
Array
(
[3] => Array
(
[0] => 4095
[2] => 651
)
[4095] => Array
(
[0] => 3
)
[651] => Array
(
[0] => 4432
)
[4432] => Array
(
[0] => 651
)
[92] => Array
(
[0] => 45
)
)
The above array has keys as student_id and the values are also student_id creating a circular relation. What I am trying to achieve is all the student_id has the same set of student_id values. Basically if student_id 3 is related to 4095, 4432 & 651, then, in turn, each of these values has to have 3 among them including other student_id from 3. The below output demonstrates what I am trying to achieve.
Array
(
[3] => Array
(
[0] => 4095
[1] => 4432
[2] => 651
)
[4095] => Array
(
[0] => 3
[1] => 4432
[2] => 651
)
[651] => Array
(
[0] => 3
[1] => 4432
[2] => 4095
)
[4432] => Array
(
[0] => 3
[1] => 4095
[2] => 651
)
[92] => Array
(
[0] => 45
)
[45] => Array
(
[0] => 92
)
)
Explanation of output
The array keys 3, 4095, 651 & 4432 are related to each other either directly or via a common relation (indirect), so will have common set of values (siblings). The key 92 in input array has a value (sibling) of 45, so in a resultant array, a new key 45 will be added to array with the inverse relation as well.
What I have tried so far
I have tried to do it with this code
$syncedSiblings = [];
foreach ($studentsWithSiblings as $sid => $siblings) {
$all = map_assoc(array_merge([$sid], array_keys($siblings)));
foreach ($all as $studentId) {
if (isset($syncedSiblings[$studentId])) {
$old = $syncedSiblings[$studentId];
$syncedSiblings[$studentId] = array_unique(array_merge($old, array_except($all, $studentId)));
} else {
$syncedSiblings[$studentId] = array_unique(array_except($all, $studentId));
}
}
}
Where $studentsWithSiblings has the above array & array_except returns array without the passed values as second argument.
This is the output I am getting right now
Array
(
[3] => Array
(
[0] => 4095
[1] => 651
)
[4095] => Array
(
[0] => 3
[1] => 651
)
[651] => Array
(
[0] => 3
[1] => 4095
[2] => 4432
)
[4432] => Array
(
[0] => 651
)
[92] => Array
(
[0] => 45
)
)
Any help with this will be highly appreciated.
If I've understood you correctly, then this possible to achieve with recursion:
function getChildren($ind_ar, $prev_ar, $data, $rem){
$tmp = [];
$mark = 0;
foreach($ind_ar as $ind){
foreach($data[$ind] as $new_val){
if(!in_array($new_val,$prev_ar) && $new_val != $ind && $new_val != $rem){
$mark = 1;
$tmp[] = $new_val;
}
foreach($data[$new_val] as $new){
if(!in_array($new,$prev_ar) && $new != $ind && $new != $rem){
$mark = 1;
$tmp[] = $new;
}
}
}
}
$res_ar = $prev_ar;
if(!empty($tmp)) $res_ar = array_unique(array_merge($tmp,$prev_ar));
if($mark) $res_ar = getChildren($tmp,$res_ar,$data, $rem);
return $res_ar;
}
You can use this function in this way:
$data = array( 3 => [4095, 651], 4095 => [3], 651 => [4432], 4432 => [3, 651], 92 => [45], 45 => [92], );
foreach($data as $in => &$data_val) {
$data_val = getChildren([$in],$data_val,$data, $in);
sort($data_val);
}
Demo
Output:
Array
(
[3] => Array
(
[0] => 651
[1] => 4095
[2] => 4432
)
[4095] => Array
(
[0] => 3
[1] => 651
[2] => 4432
)
[651] => Array
(
[0] => 3
[1] => 4095
[2] => 4432
)
[4432] => Array
(
[0] => 3
[1] => 651
[2] => 4095
)
[92] => Array
(
[0] => 45
)
[45] => Array
(
[0] => 92
)
)
Two nested loops over the data. If the keys are different, then check if the key of the inner loop is already contained in the data array of the outer key element - if not, add it.
$data = json_decode('{"3":{"0":4095,"2":651},"4095":[3],"651":[4432],"4432":{"1":651}}', true);
foreach($data as $key_outer => $val_outer) {
foreach($data as $key_inner => $val_inner) {
if($key_outer != $key_inner && !in_array($key_inner, $data[$key_outer])) {
$data[$key_outer][] = $key_inner;
}
}
}
var_dump($data);
This gets you
array (size=4)
3 =>
array (size=3)
0 => int 4095
2 => int 651
3 => int 4432
4095 =>
array (size=3)
0 => int 3
1 => int 651
2 => int 4432
651 =>
array (size=3)
0 => int 4432
1 => int 3
2 => int 4095
4432 =>
array (size=3)
1 => int 651
2 => int 3
3 => int 4095
I am assuming a specific order of the elements in those sub-items is not actually required. If it is, then please sort them yourself as desired afterwards or in between (depending on what exactly you need, f.e. sort($data[$key_outer]); after the inner loop would get you the IDs in all sub-arrays sorted ascending.)
I want to display the unique pairs values in array.and to print the pair only if addition of that pair is even number.Language to be used is PHP.
As you aren't explain well in your question but I tried , Maybe helpful.
<?php
$range1 = range(1,2000);//change as per your requirement
$i = 5; //change as per your requirement
$UniqueEvenPairs = array();
while($i > 0){
shuffle($range1);
$addition = (($range1[0] + $range1[10]));
if($addition % 2 == 0){
$UniqueEvenPairs[$i] = array("val_1"=>$range1[0] , "val_2"=>$range1[10] , "addition" =>$addition);
$i--;
}
}
echo "<pre>";print_r($UniqueEvenPairs);
?>
OutPut
Array
(
[5] => Array
(
[val_1] => 836
[val_2] => 500
[addition] => 1336
)
[4] => Array
(
[val_1] => 293
[val_2] => 319
[addition] => 612
)
[3] => Array
(
[val_1] => 1604
[val_2] => 742
[addition] => 2346
)
[2] => Array
(
[val_1] => 432
[val_2] => 1606
[addition] => 2038
)
[1] => Array
(
[val_1] => 896
[val_2] => 1766
[addition] => 2662
)
)
My Array is below
$sample_arr = Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 20
[ref] => ref 2
)
[2] => Array
(
[index] => 2
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 21
[ref] => ref 2
)
)
As you can see in the above array there is article_Id twice in the array with value 6
I would like to find the details of the second row so that I can make the second row qty 41 i.e my result array will be like the one below
I have tried the in_array function but still there is something missing
I also tried with the foreach but the problem is that how to get the first appearance row qty? i.e in the $sample_arr when the user adds the third record with article_Id 6 the second row must be updated as shown below
$result_arr = Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref goes here
)
)
Looks like article ID is unique. So, we can kep storing data in this $newArray variable with the key as article ID.
Every time, it's checked if a record containing the article id exists. If so, the quantity is added. If not, it's appended to the $newArray.
$newArray = array();
foreach($sample_arr as $arr) {
if (isset($newArray[$arr['article_Id']])) {
$newArray[$arr['article_Id']]['qty'] += $arr['qty'];
$newArray[$arr['article_Id']]['ref'] = 'Ref goes here'; // If this the string that replaces the ref
} else {
$newArray[$arr['article_Id']] = $arr;
}
}
$newArray = array_values($newArray);
Output:
Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
Try the following:
$new_merged_array = array();
if(!empty($sample_arr )){
foreach($sample_arr as $sample_ar){
if(!empty($sample_ar) && isset($sample_ar['article_Id'])){
if(isset($new_merged_array[$sample_ar['article_Id']])){
$new_merged_array[$sample_ar['article_Id']]['qty'] += $sample_ar['qty'];
}else{
$new_merged_array[$sample_ar['article_Id']] = $sample_ar;
}
}
}
}
print_r($new_merged_array);
Output will be:
Array(
[4] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[6] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
Another way:
$new_merged_array = $sample_array = array();
if(!empty($sample_arr )){
foreach($sample_arr as $sample_ar){
if(!empty($sample_ar) && isset($sample_ar['article_Id'])){
if(isset($new_merged_array[$sample_ar['article_Id']])){
$new_merged_array[$sample_ar['article_Id']]['qty'] += $sample_ar['qty'];
}else{
$new_merged_array[$sample_ar['article_Id']] = $sample_ar;
}
}
}
}
if(!empty($new_merged_array )){
foreach($new_merged_array as $new_merged_arr){
$sample_array[] = $new_merged_arr;
}
}
print_r($sample_array);
Output will be:
Array(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
$sample_arr = array
(
0 => array
(
'index'=> 0,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 4,
'qty' => 50,
'ref' => 'ref'
),
1 => array
(
'index' => 1,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 6,
'qty' => 20,
'ref' => 'ref 2'
),
2 => array
(
'index' => 2,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 6,
'qty' => 21,
'ref' => 'ref 2'
)
);
$articleArray = [];
foreach($sample_arr as $key=>$value){
$articleId = $value['article_Id'];
if(array_key_exists($articleId,$articleArray)){
$articleArray[$articleId]['qty'] = $articleArray[$articleId]['qty'] + $value['qty'];
}else{
$articleArray[$articleId] = $value;
}
}
$articleArray = array_values($articleArray);
print_r($sample_arr);
print_r($articleArray);
Demo
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
I have one array which I am getting from database query response.
Now I want to count same categories and print in option_name array.
I have tried it with different array functions but want get desire output.
I have one idea to take new array and push it with foreach loop but not much idea of how can i achieve using code. Please help me to solve it.
Array
(
[0] => Array
(
[CNC] => Array
(
[id] => 5
[category_id] => 68
)
[GVO] => Array
(
[option_name] => Actors
)
)
[1] => Array
(
[CNC] => Array
(
[id] => 11
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[2] => Array
(
[CNC] => Array
(
[id] => 3
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[3] => Array
(
[CNC] => Array
(
[id] => 4
[category_id] => 74
)
[GVO] => Array
(
[option_name] => Musician
)
)
[4] => Array
(
[CNC] => Array
(
[id] => 7
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
[5] => Array
(
[CNC] => Array
(
[id] => 6
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
)
Desire Output:
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Thanks in advance!
You simply need to loop through the array using foreach like as
$result = [];
foreach($arr as $k => $v){
if(isset($result[$v['GVO']['option_name']])){
$result[$v['GVO']['option_name']] += 1;
}else{
$result[$v['GVO']['option_name']] = 1;
}
}
print_R($result);
You can count the option_name values by incrementing a counter in an associative array where the key is the option_name:
$counts = [];
foreach($array as $v) {
if(!isset($counts[$v['GVO']['option_name']])) {
$counts[$v['GVO']['option_name']] = 0;
}
$counts[$v['GVO']['option_name']]++;
}
print_r($counts);
Try this:
$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
if(in_array($value, $new_array)){
$new_array[$value] = $new_array[$value]+1;
}else{
$new_array[$value] = 1;
}
}
Output
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
I have an array structure like this and wanted to Re-arrange it to the one below. Any suggestions for a faster/simple fix? I already did the addition of the dates. Thanks! :)
Input:
Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
[company_name] => Company_A
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
[company_name] => Company_A
)
[2] => Array
(
[user_id] => 25
[display_name] => Hulk
[company_name] => Company_B
)
[3] => Array
(
[user_id] => 50
[display_name] => Bob
[company_name] => Company_B
)
)
Output:
Array
(
[Company_A] => Array
(
[company_total_hours] => 20h 45m
[employees] => Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
)
)
)
[Company_B] => Array
(
[company_total_hours] => 7h 30m
[employees] => Array
(
[0] => Array
(
[user_id] => 25
[display_name] => Hulk
)
[1] => Array
(
[user_id] => 50
[display_name] => Bob
)
)
)
)
My Attempts:
<?php
$company_names = array();
foreach ($records as $k => $v) {
$company_names[] = $v->company_name;
}
$company_names = array_unique($company_names);
// hard coded testing
if (count($company_names) > 0) {
foreach($company_names as $k2 => $v2) {
$final_array[$v2]['company_total_hours'] = rand(1, 20);
$final_array[$v2]['employees'] = array(
array('user_id' => '255', 'display_name' => 'Mark'),
array('user_id' => '150', 'display_name' => 'Paul')
);
}
}
// on-going testing right now here....
I don't see where you derive your hours from so I left that out.
$i = 0;
foreach($vals as $keys => $arrays) {
if(!isset($new[$arrays['company_name']]))
$i = 0;
$new[$arrays['company_name']]['employees'][$i]['display_name'] = $arrays['display_name'];
$new[$arrays['company_name']]['employees'][$i]['user_id'] = $arrays['user_id'];
$i++;
}
Gives you:
Array
(
[Company_A] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Mark
[user_id] => 255
)
[1] => Array
(
[display_name] => Paul
[user_id] => 150
)
)
)
[Company_B] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Hulk
[user_id] => 25
)
[1] => Array
(
[display_name] => Bob
[user_id] => 50
)
)
)
)
foreach($arr as $v)
{
if(!$arr2[$v['company_name']]['employees'])
$arr2[$v['company_name']]['employees'] = array();
if(!$arr2[$v['company_name']]['company_total_hours'])
$arr2[$v['company_name']]['company_total_hours'] = '2h';//addional value
$arr2[$v['company_name']]['employees'][] = array('user_id'=>$v['user_id'],
'display_name'=>$v['display_name']
);
}
I have created a function which does the same thing as the answer given by #Rasclatt.
function groupByKeyValue($array, $oldKeyName, $newKeyName){
$newArray = array();
foreach($array as $key=>$value){
if(isset($newArray[$value[$oldKeyName]][$newKeyName])){
$newArray[$value[$oldKeyName]][$newKeyName][] = array('user_id'=> $value['user_id'], 'display_name' => $value['display_name']);
}else{
$newArray[$value[$oldKeyName]] = array($newKeyName => array(array('user_id'=> $value['user_id'], 'display_name' => $value['display_name'])));
}
}
return $newArray;
}
//usage
$newArray = groupByKeyValue($array, 'company_name', 'employees');
You can add a third parameter to send the keys for the array values which needs to be used in the new array for 'employees'. Please check this link for the working of the function http://goo.gl/I6Of5y