phparrayscodeigniter

Undefined index error while trying to access multidimensional array data in CodeIgniter


When I do this :

$this->load->library('mcapi');
$this->load->config('mcapi', TRUE);

// get list members
$retval = $this->mcapi->listMembers('0000000', 'subscribed', null, 0, 5000 );

foreach ($retval as $member) {
    echo $member['email'] . " - " . $member['timestamp'] . "\n";
}

I get this error:

A PHP Error was encountered  
Severity: Notice    
Message: Undefined index: email    
Filename: tabs/mailchimp.php    
Line Number: 18

But When I print the array with print_r(), it works fine.

$retval = $this->CI->mcapi->listMembers('0000000', 'subscribed', null, 0, 5000);
print_r($retval);

I get the data like this:

Array (
    [total] => 2
    [data] => Array (
        [0] => Array (
            [email] => email@gmail.com
            [timestamp] => 2012-01-06 09:29:31
        ) 
    )
)

Solution

  • You need to do <?php foreach($retval['data'] as $member) { } ?> - the array containing the 'email' key is nested inside the data array.