Mailchimp: Get random member info

348 Views Asked by At

This is my first time using the MailChimp API, I've been looking at some examples and trying to figure out this on my own but I can't seem to be able to get what I need.

I only have one list on my account and I'm trying to run a contest where I choose one random winner from the list. So far I've managed to retrieve the total number of members on the list, and from that I have generated a random number to be used as the 'winner'. Now I need to find the member from the list located in that position from the list members array, but I'm not sure how to go about it.

This is what I have so far:

include "Mailchimp.php";

/* Load member count */
function mcg_mc_sub_count() {
    $MailChimp = new MailChimp('*****');
    $list = $MailChimp->call('lists/list');
    $total_members .= $list[data][0][stats][member_count];
    return number_format($total_members);
}   

/* Generate random number */
function mcg_mc_random_number() {
    $total_members = mcg_mc_sub_count();
    $random_number = rand(1, $total_members);
    return $random_number;
}

I think at this point I should be using $MailChimp->call('lists/member-info'); but since I only have a random position and not a member id/email, I'm not sure which parameters to use or how to go about it.

Any help is appreciated figuring this method out or through a different way, thanks!

2

There are 2 best solutions below

0
On

I think your logic is correct. MailChimp does not provide an API for random member, but you can get list and create randon function in the array.

Example:

Start by use-ing the class and creating an instance with your API key

use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');

Then, list all the mailing lists (with a get on the lists method)

$result = $MailChimp->get('lists');
print_r($result);

So, with the list, you can call the members and put in the array. Then you can use some function to get a random value in the array.

$input = array("Member 1", "Member 2", "Member 3", "Member 4", "Member 5");
$rand_keys = array_rand($input, 1);
echo $input[$rand_keys[0]] . "\n";

Refs:

0
On

First, it's worth noting that you're using a version of the MailChimp API that is going to go away at the end of the year. Just in case this is a one-time script, here's the way to do this in v2.0 that doesn't require downloading your entire list (the same concept will work in v3 with some slight alterations):

Once you have the number of people on the list, go ahead and generate your random number. Then, use the lists/members endpoint with the start parameter equal to one less than your random number and the limit parameter equal to 1.

That should return the exact subscriber you're looking for without requiring you to download the entire list.