Mamulasa
Mamulasa

Reputation: 543

Laravel 5 Loop Through Array

I am passing a variable $mailchimp from my Controller to my View.

this is what I got with {{dd($mailchimp)}}

    array:8 [▼
      "id" => "xyz123"
      "email_address" => "[email protected]"
      "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"
    ]

how can I loop through this array ($mailchimp) ? With the code below I get an exception: "htmlentities() expects parameter 1 to be string, array given"

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

Update: With this Code in My Controller

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);
}

I need to iterate the mailchimp array. As there are multiple users, alexey's suggestion doesn't work out anymore.

This stil doesn't work:

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

Upvotes: 2

Views: 5420

Answers (2)

Armin Sam
Armin Sam

Reputation: 933

Since you are only interested in printing the values in your array, you can use array_flatten to get rid of the nested arrays, and then loop through the result:

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

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You don't need to iterate over $user. If $mailchimp is an array of users, do this:

  {{ $mailchimp['email_adress'] }}
  {{ $mailchimp['merge_fields']['FNAME'] }} {{ $mailchimp['merge_fields']['LNAME'] }}

Upvotes: 2

Related Questions