Laravel循环通过多维数组

时间:2016-10-28 14:28:05

标签: php laravel foreach

我试图在我看来循环遍历一个多维数组。

数组(我将$ mailchimp从我的控制器传递给我的视图)是:

    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 [▶]
    ]

在我看来使用此代码:

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

抛出异常:为foreach()提供的参数无效

有人可以告诉我如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你期望每个第一个数组的值也是一个数组。情况并非如此,只有第一个数组中的某些值是数组,因此必须设置条件。您可以使用is_array帮助程序查看第一个数组中的值是否为实际数组,如果是,则循环遍历每个数组。

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

答案 1 :(得分:0)

正如卡洛斯所提到的,您遇到的主要问题是因为您试图回应数组find his answer here

关于您的第二个问题Thanks Carlos. It tried you solution with this result: htmlentities() expects parameter 1 to be string, array given您是否在该页面上有任何其他代码,可能是{{Form :: text(&#39; something&#39;,$ array)}}