简体   繁体   中英

Laravel Loop Through Multidimesional Array

I am trying to loop through a multidimensional array in my view.

the array (I am passing $mailchimp from my controller to my view) is:

    array:19 [▼
      "id" => "f3200e9cc5a900bb7c075103b871232f0"
      "email_address" => "john.doe@discworld.com"
      "unique_email_id" => "xalasd"
      "email_type" => "html"
      "status" => "subscribed"
      "merge_fields" => array:2 [▼
        "FNAME" => "John"
        "LNAME" => "Doe"
      ]
      "stats" => array:2 [▶]
      "ip_signup" => ""
      "timestamp_signup" => ""
      "ip_opt" => "93.212.91.32"
      "timestamp_opt" => "2016-10-27T13:53:02+00:00"
      "member_rating" => 2
      "last_changed" => "2016-10-27T13:53:02+00:00"
      "language" => ""
      "vip" => false
      "email_client" => ""
      "location" => array:6 [▶]
      "list_id" => "76980934492"
      "_links" => array:8 [▶]
    ]

With this Code in my view:

@foreach($mailchimp as $user)
    @foreach($user as $key => $value)
      <ul>
        <li>{{$value}}</li>
       </ul>
     @endforeach
@endforeach

An exception is thrown: Invalid argument supplied for foreach()

Can somebody tell me how to fix this ?

you are expecting for the value of each of the first array to also be an array. That is not the case, only some values from the first array is an array, so you must put a condition. You can use the is_array helper to see if the value from the first array is an actual array, if so, loop thru each one of those.

foreach($a as $b){
    if(is_array($b)){
        foreach($b as $c){
            echo($c);
        }
    }
}

As mentioned by Carlos the main issue you're encountering is because you're trying to echo an array find his answer here .

Regarding your second issue Thanks Carlos. It tried you solution with this result: htmlentities() expects parameter 1 to be string, array given Thanks Carlos. It tried you solution with this result: htmlentities() expects parameter 1 to be string, array given do you have any other code on that page, perhaps {{ Form::text('something', $array) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM