如何遍历这个PHP数组

时间:2014-03-30 01:00:48

标签: php arrays

我正在从GetResponse Email Marketing API检索信息,我的代码从数组中返回此数据:

array(2) {
  ["zAuW"]=>
  object(stdClass)#332 (7) {
    ["optin"]=>
    string(6) "double"
    ["from_email"]=>
    string(17) "email@gmail.com"
    ["name"]=>
    string(23) "asw_getresponse_edition"
    ["description"]=>
    NULL
    ["reply_to_email"]=>
    string(17) "email@gmail.com"
    ["created_on"]=>
    string(19) "2014-03-29 07:27:46"
    ["from_name"]=>
    string(11) "1213456@"
  }
  ["z1Bi"]=>
  object(stdClass)#333 (7) {
    ["optin"]=>
    string(6) "double"
    ["from_email"]=>
    string(17) "email@gmail.com"
    ["name"]=>
    string(7) "test"
    ["description"]=>
    NULL
    ["reply_to_email"]=>
    string(17) "email@gmail.com"
    ["created_on"]=>
    string(19) "2014-03-29 02:54:51"
    ["from_name"]=>
    string(11) "123456@"
  }
}
object(stdClass)#330 (1) {
  ["zAuW"]=>
  object(stdClass)#334 (7) {
    ["optin"]=>
    string(6) "double"
    ["from_email"]=>
    string(17) "email@gmail.com"
    ["name"]=>
    string(23) "asw_getresponse_edition"
    ["description"]=>
    NULL
    ["reply_to_email"]=>
    string(17) "email@gmail.com"
    ["created_on"]=>
    string(19) "2014-03-29 07:27:46"
    ["from_name"]=>
    string(11) "123456@"
  }
}

以下是用于获取此数据的代码:

require_once('GetResponseAPI.class.php');
$api = new GetResponse('YOUR_API_KEY');

// Account
$details = $api->getAccountInfo();
//var_dump($details);

// Campaigns
$campaigns = (array)$api->getCampaigns();
$campaignIDs = array_keys($campaigns);
$campaign = $api->getCampaignByID($campaignIDs[0]);
var_dump($campaigns, $campaign);

我想知道我可以使用什么PHP代码循环遍历此数组并在下拉列表中显示信息。我试过这个,但这显然是错误的:

$output .= '<select class="asw_select'.$field_class.'" name="'.$this->prefix.'_options['.$id.']" id="'.$this->prefix.'_options['.$id.']">';
foreach($campaign as $key => $value)
    $output .= '<option '.selected($current_mailing_list, $value['id'], false).' id="'.esc_attr($value['id']).'" value="'.$value['id'].'">'. __($value['name'], $this->prefix).'</option>';
$output .= '</select>';

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您的回复中有array objects。因此,在foreach循环中,您应该访问$value->name之类的元素(而不是$value['name']

您的值没有id属性。因此,经过上述修正后,$value->id将为空。但是,$key似乎是我的唯一标识符。如果是这种情况,您可以在foreach循环中将$value->id替换为$key

$output.= '<select class="asw_select'.$field_class.'" name="'.$this->prefix.'_options['.$id.']" id="'.$this->prefix.'_options['.$id.']">';
foreach($campaign as $key => $value)
    $output .= '<option '.selected($current_mailing_list, $key, false).' id="'.esc_attr($key).'" value="'.$key.'">'. __($value->name, $this->prefix).'</option>';
$output .= '</select>';