This question already has answers here:
How to count array with group by
(2 answers)
Closed 4 months ago.
I am creating a notification system. That results shown below returns all notifications for a particular user. I want to group the array by 'notify_id' and also count each item in a group.
Such that I'll have :
"Jack Bill is now following you", John Doe commented on your post 2",
"John Doe and 2 others commented on your post 1"
Array ( [0] =>
Array ( [id] => 1
[user_id] => 10
[type] => follow
[notify_id] => 13
[notify_date] => 1483444712
[firstname] => Jack
[surname] => Bill
[picture] => )
[1] =>
Array ( [id] => 10
[user_id] => 10
[type] => comment
[notify_id] => 2
[notify_date] => 1482159309
[firstname] => John
[surname] => Doe
[picture] => )
[2] =>
Array ( [id] => 8
[user_id] => 10
[type] => comment
[notify_id] => 1
[notify_date] => 1482159219
[firstname] => John
[surname] => Doe
[picture] => )
[3] =>
Array ( [id] => 6
[user_id] => 16
[type] => comment
[notify_id] => 1
[notify_date] => 1482159129
[firstname] => James
[surname] => Canon
[picture] => )
[4] =>
Array ( [id] => 5
[user_id] => 14
[type] => comment
[notify_id] => 1
[notify_date] => 1482159079
[firstname] => Sharon
[surname] => Abba
[picture] => ) )
You have two questions, I will try to answer both of them:
I want to group the array by 'notify_id'...
Assuming your array name is $a:
$return = array();
foreach($a as $val) {
if (!isset($return[$val['notify_id']])) {
$return[$val['notify_id']] = array();
}
$return[$val['notify_id']][] = $val;
}
print_r($return); // <-- Your array is grouped by notify_id
... and also count each item in a group.
Now you have your grouped by notify_id in $return so:
foreach($return as $k => $v) {
echo count($v) . ' values are present for notify #' . $k;
// It will display something like: 10 values are present for notify #1
}
Hope it will help, good luck!
Related
This question already has answers here:
Return single column from a multi-dimensional array [duplicate]
(7 answers)
Closed 5 years ago.
I got the next array:
Array (
[0] => Array ( [email] => xasxxxxxx#yahoo.com [btc] => 0.00287896 [tn] => 6.615 [address] => 2BY4HM [status] => pending )
[1] => Array ( [email] => xxxxx#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
[2] => Array ( [email] => xsxxxx#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
[3] => Array ( [email] => xssasas5#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
[4] => Array ( [email] => xxxxxx#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
)
How am I supposed to get all 'address'es in a variable as a string separated by comma?
something like this
$string = "1stadress, 2ndaddress, 3ndadress' etc
I tried:
$comma_separated = implode(",", $row['address']); // where $ row is the array above
and it failed.
You can use array_column and implode
echo implode(',',array_column($myarray,'address'));
Loop though array and collect the relevant members, I'd perefer using untermidiate array this way it can be reused if needed later
$buffer = [];
foreach($myArray as $id=>$data){
$buffer[] = $data['address'];
}
$output = implode(',',$buffer);
I have made researches and havent fount any solutions for this yet. So final thought is come to Stackoverflow and ask the question.
I have 2 array like below:
BigArray
Array
(
[0] => Array
(
[id] => 1
[category_name] => Accountancy
[category_name_vi] => Kế toán
[category_id] => 1
)
[1] => Array
(
[id] => 2
[category_name] => Armed forces
[category_name_vi] => Quân đội
[category_id] => 2
)
[2] => Array
(
[id] => 3
[category_name] => Admin & Secretarial
[category_name_vi] => Thư ký & Hành chính
[category_id] => 3
)
[3] => Array
(
[id] => 4
[category_name] => Banking & Finance
[category_name_vi] => Tài chính & Ngân hàng
[category_id] => 4
)
)
and SmallArray:
Array
(
[0] => Array
(
[id] => 7
[category_id] => 2
[jobseeker_id] => 1
)
[1] => Array
(
[id] => 8
[category_id] => 3
[jobseeker_id] => 1
)
)
Ok, now I wanted to match each category_id from SmallArray link with respectively category_name from BigArrayand the output I only need matched values between SmallArray and BigArraywhere category_id of SmallArray is key and category_name of BigArray is value like below:
Matched array:
Array
(
[0] => Array
(
[2] => Armed forces
)
[1] => Array
(
[3] => Admin & Secretarial
)
)
So far, I have tried array_intersect, 2 foreach loops but no luck. Any advise would be very appreciated :(
Thanks
This should do that:
foreach ($smallArray as $smallKey => $smallElement) {
foreach ($bigArray as $bigKey => $bigElement) {
if ($bigElement['id'] == $smallElement['category_id']) {
$smallArray[$smallKey] = array(
$bigElement['id'] => $bigElement['category_name'],
);
break; // for performance and no extra looping
}
}
}
After these loops, you have what you want in $smallArray.
I have a problem. I am trying to count the array keys in my array using an specific element inside my array in the main array
public function index()
{
$user=User::all();
$lead=Lead::all();
$role=Role::all();
$lead=DB::table('lead')
->select(DB::raw('lead.id','users.number','users.username', 'lead.leadid','lead.first_name', 'lead.last_name','lead.email' ,count('lead.email') ))
->where ('lead.email', '>', 1)
->groupBy('lead.email')
->leftJoin('users', 'users.number', '=', 'lead.assign')
->get();
$user=DB::table('users')->select('users.number','users.username')->get();
echo "<pre>";
print_r($lead);
die();
}
Here is the output when I print it out
Array
(
[0] => Array
(
[id] => 63
[number] => 3
[username] => shankar
[leadid] => zcrm_125720000016007771
[first_name] =>
[last_name] => Amoah Owusu Richmond
[email] => ramoahhowusu50#gmail.com
)
[1] => Array
(
[id] => 64
[number] => 3
[username] => shankar
[leadid] => zcrm_125720000016007733
[first_name] => Deus
[last_name] => mathew
[email] => mathewdeus#gmail.com
)
[2] => Array
(
[id] => 65
[number] => 2
[username] => james
[leadid] => zcrm_125720000016007737
[first_name] => bari
[last_name] => safi
[email] => barisafi57#gmail.com
)
[3] => Array
(
[id] => 66
[number] => 11
[username] => nishupandey
[leadid] => zcrm_125720000016007741
[first_name] => Noorahmad
[last_name] => Noor
[email] => noorahmad.noor81#gmail.com
)
[4] => Array
(
[id] => 67
[number] => 12
[username] => ravi123
[leadid] => zcrm_125720000016007747
[first_name] => munsanje
[last_name] => nakeempa
[email] => mnakeempa#yahoo.com
)
[5] => Array
(
[id] => 68
[number] => 8
[username] => veerkishor
[leadid] => zcrm_125720000016007751
[first_name] => Noorahmad
[last_name] => Noor
[email] => noorahmad.noor71#gmail.com
)
[6] => Array
(
[id] => 69
[number] => 13
[username] => rahul
[leadid] => zcrm_125720000016007755
[first_name] => painad
[last_name] => sherzad
[email] => painda12sherzad#gmail.com
)
)
I want to count the elements using the email and check how many times the element is appearing in the array. Am trying to use the array_count_values but am not quite sure how to use it. Thanks in advance
Try this:
In your DB::raw, you need to put "count" inside quotes. Otherwise, you will just run php count (like sizeof).
<?php
$lead=DB::table('lead')
->select(['lead.id','users.number','users.username', 'lead.leadid','lead.first_name', 'lead.last_name','lead.email'])
->select( DB::raw( "count('lead.email') as total") )
->where ('lead.email', '>', 1)
->groupBy('lead.email')
->leftJoin('users', 'users.number', '=', 'lead.assign')
->get();
If you want to count the number of arrays with specific property inside on big array then you need to loop over all the outer array elements and check the inner array elements.
To count how many elements have the same e-mail, I guess you have to do it manually...
$emails = array();
foreach ($lead as $lineNumber => $line) {
$email = $line['email'];
if(array_key_exists("$email",$emails) {
$emails["$email"]++;
} else {
$emails["$email"] = 1;
}
}
echo "<pre>";
print_r($emails);
Is that what you want ?
Simply Use Count ($array) which u want to count
hope it will work
I am decoding JSON from an API:
$api = "http://xyzdomain.com/api";
$json = file_get_contents($api);
$array = json_decode($json,true);
print_r($array);
Here is the sample result of API objects and arrays.
Array
(
[status] => ok
[count] => 1
[meta] => Array
(
[count] => 1
)
[data] => Array
(
[accountid] => Array
(
[0] => Array
(
[all] => Array
(
[fans] => 16
[user post] => 333
[user Details] => xyz
)
[scorelist] => 1
[name] => John Doe 1
[timespent] => 5887
[nation] => usa
)
[1] => Array
(
[all] => Array
(
[fans] => 123
[user post] => 903
[user Details] => mno
)
[scorelist] => 6
[name] => John Doe 2
[timespent] => 1269
[nation] => usa
)
[2] => Array
(
[all] => Array
(
[fans] => 16
[user post] => 303
[user Details] => abc
)
[scorelist] => 1
[name] => John Doe 3
[timespent] => 9292
[nation] => ussr
)
[3] => Array
(
[all] => Array
(
[fans] => 16
[user post] => 333
[user Details] => jqr
)
[scorelist] => 1
[name] => John Doe 4
[timespent] => 75600
[nation] => usa
)
)
)
)
I used only three samples above, but it may go up to 500 or more.
I have basically two questions here:
I want to make a table using jqgrid or datatables or any other way it looks good.
How can I sum timespent where nation is, say, USA in above example?
$timespent_usa = 0;
foreach($array['data']['accountid'] as $account) {
if ($account['nation'] == 'usa') {
$timespent_usa += $account['timespent'];
}
}
echo $timespent_usa;
I'm not sure on how you plan on getting the data into datatables, you could just echo the data within each $account array within the foreach loop into <td> elements.
Q: How to Search Massive Multi-Dimensional Array for Single Value, and Return Parent Array?
I have this massive json that represents all of the achievements in WoW.
http://us.battle.net/api/wow/data/character/achievements
I converted it into an array using json_decode. This then leaves me with a very massive array that I need to search all of its levels until I find a specific value, I then need to return the parent array of that value.
ex:
This is one small part of the decoded array.
[0] => Array
(
[id] => 7385
[title] => Pub Crawl
[points] => 10
[description] => Complete the Brewmaster scenario achievements listed below.
[reward] => Reward: Honorary Brewmaster Keg
[rewardItems] => Array
(
[0] => Array
(
[id] => 87528
[name] => Honorary Brewmaster Keg
[icon] => inv_holiday_brewfestbuff_01
[quality] => 3
[itemLevel] => 90
[tooltipParams] => Array
(
)
[stats] => Array
(
)
[armor] => 0
)
)
[icon] => inv_misc_archaeology_vrykuldrinkinghorn
[criteria] => Array
(
[0] => Array
(
[id] => 20680
[description] => Spell No Evil
[orderIndex] => 0
[max] => 1
)
[1] => Array
(
[id] => 20681
[description] => Yaungolian Barbecue
[orderIndex] => 1
[max] => 1
)
[2] => Array
(
[id] => 20682
[description] => Binan Village All-Star
[orderIndex] => 2
[max] => 1
)
[3] => Array
(
[id] => 20683
[description] => The Keg Runner
[orderIndex] => 3
[max] => 1
)
[4] => Array
(
[id] => 20684
[description] => Monkey in the Middle
[orderIndex] => 4
[max] => 1
)
[5] => Array
(
[id] => 20685
[description] => Monkey See, Monkey Kill
[orderIndex] => 5
[max] => 1
)
[6] => Array
(
[id] => 20686
[description] => Don't Shake the Keg
[orderIndex] => 6
[max] => 1
)
[7] => Array
(
[id] => 20687
[description] => Party of Six
[orderIndex] => 7
[max] => 1
)
[8] => Array
(
[id] => 20688
[description] => The Perfect Pour
[orderIndex] => 8
[max] => 1
)
[9] => Array
( re
[id] => 20689
[description] => Save it for Later
[orderIndex] => 9
[max] => 1
)
[10] => Array
(
[id] => 20690
[description] => Perfect Delivery
[orderIndex] => 10
[max] => 1
)
)
[accountWide] =>
[factionId] => 2
)
I am attempting to create a function where I can just simply enter the achievement ID, which in this exmple is 7385, and have the parent array which would be [0] => Array (...); returned, so i can then grab the achievement details from that array.
I am not sure if this is really a proper question, as I am not sure as where to start.
So far I have just started breaking the original massive array down into its 10 equally as massive categories, and then searching them each individually, but I would like to just be able to search the main array once instead of searching each category array individually.
ex:
$allAchieves = file_get_contents('http://us.battle.net/api/wow/data/character/achievements');
$allAchieves = json_decode($allAchieves, true);
$generalAchieves = $allAchieves[achievements][0][achievements];
$quests = $allAchieves[achievements][1][categories];
$explorationAchieves = $allAchieves[achievements][2][categories];
$pvp = $allAchieves[achievements][3][categories];
$dungeonAndRaids = $allAchieves[achievements][4][categories];
$professions = $allAchieves[achievements][5][categories];
$reputation = $allAchieves[achievements][6][categories];
$scenarios = $allAchieves[achievements][7][categories];
$worldEvents = $allAchieves[achievements][8][categories];
$petbattle = $allAchieves[achievements][9][categories];
$featsOfStrength = $allAchieves[achievements][10][categories];
Hopefully someone can help, as the other threads I have seen sofar on array searching seem too simple to be of any help as the arrays they are dealing with are nothing to the size of the one I have here.
Thanks for the suggestions, but I solved the issue using a different approach found here:
http://us.battle.net/wow/en/forum/topic/8892160022?page=1#4