Laravel 5 Loop Through Array

时间:2016-11-02 09:06:53

标签: php laravel foreach

我将变量$mailchimp从我的Controller传递给我的视图。

这是我用{{dd($mailchimp)}}

得到的
    array:8 [▼
      "id" => "xyz123"
      "email_address" => "john.doe@discworld.com"
      "unique_email_id" => "c9a36649c8"
      "email_type" => "html"
      "status" => "subscribed"
      "merge_fields" => array:2 [▼
        "FNAME" => "John"
        "LNAME" => "Doe"
      ]
      "stats" => array:2 [▼
        "avg_open_rate" => 0
        "avg_click_rate" => 0
      ]
      "list_id" => "769808qeqw92"
    ]

我如何循环遍历此数组($ mailchimp)?使用下面的代码我得到一个例外:“htmlentities()期望参数1是字符串,给定数组”

@foreach($mailchimp as $user)
  @if(is_array($user))
    @foreach($user as $key => $value)
      {{$value}}
    @endforeach
  @endif
@endforeach

更新: 在我的控制器中使用此代码

public function index()
{   //Fetch all subscribers from DB
    $subscribers = Subscriber::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->get();

    foreach ($subscribers as $key => $subscriber) {
      //Check if the local subscriber is also present in mailchimp
      $mailchimp = Newsletter::getMember($subscriber->email);
    }

    return view('backend.newsletter.contacts.index')->withSubscribers($subscribers)
                                                    ->withMailchimp($mailchimp);
}

我需要迭代mailchimp数组。由于有多个用户,alexey的建议不再适用。

此stil不起作用:

@foreach($mailchimp as $key => $user)
    {{$user}}
  @endforeach

2 个答案:

答案 0 :(得分:1)

您不需要迭代int(a.size())-int(b.size())-1 。如果$user是一组用户,请执行以下操作:

$mailchimp

答案 1 :(得分:0)

由于您只对打印数组中的值感兴趣,因此可以使用array_flatten删除嵌套数组,然后遍历结果:

@foreach(array_flatten($mailchimp) as $userData)    
    {{$userData}} 
@endforeach