使用集合循环遍历数组

Posted

技术标签:

【中文标题】使用集合循环遍历数组【英文标题】:Looping through an array with a collection 【发布时间】:2021-09-12 05:32:23 【问题描述】:

我正在使用 Laravel ViewModels 重构从 API 返回的数据。 以下是我用来格式化特定数据的函数

 public function similar()
    
        $similarCollection = collect($this->similar)->map(function($movie)

            return collect($movie)->merge([
                'poster_path' => $movie['poster_path'] ? 
                  'https://image.tmdb.org/t/p/w500/'.$movie['poster_path']
                   : 'https://via.placeholder.com/500x750?text='.$movie['title'],
                'backdrop_path' =>  $movie['backdrop_path'] 
                   ?'https://image.tmdb.org/t/p/original/'.$movie['backdrop_path']
                    :'https://via.placeholder.com/500x750?text='.$movie['title'],

            ])->only([
                'poster_path','title','backdrop_path','backdrop_path'
            ]);

        );

         dd($similarCollection);

    

上面的函数在dd()之后返回下面的数组

 Illuminate\Support\Collection #394 ▼
  #items: array:20 [▼
    0 => Illuminate\Support\Collection #357 ▼
      #items: array:3 [▼
        "title" => "The Fox and the Hound"
        "backdrop_path" => "https://image.tmdb.org/t/p/original//87uShMszqPxwA034GsskGdzJOgN.jpg"
        "poster_path" => "https://image.tmdb.org/t/p/w500//1382VHxqZDXu2t8i46zf4fP71JG.jpg"
      ]
    
    1 => Illuminate\Support\Collection #359 ▶
    2 => Illuminate\Support\Collection #358 ▶
    3 => Illuminate\Support\Collection #374 ▶
    4 => Illuminate\Support\Collection #371 ▶
    5 => Illuminate\Support\Collection #361 ▶
    6 => Illuminate\Support\Collection #362 ▶
    7 => Illuminate\Support\Collection #363 ▶
    8 => Illuminate\Support\Collection #366 ▶
    9 => Illuminate\Support\Collection #367 ▶
    10 => Illuminate\Support\Collection #354 ▶
    11 => Illuminate\Support\Collection #353 ▶
    12 => Illuminate\Support\Collection #360 ▶
    13 => Illuminate\Support\Collection #403 ▶
    14 => Illuminate\Support\Collection #401 ▶
    15 => Illuminate\Support\Collection #396 ▶
    16 => Illuminate\Support\Collection #400 ▶
    17 => Illuminate\Support\Collection #402 ▶
    18 => Illuminate\Support\Collection #368 ▶
    19 => Illuminate\Support\Collection #395 ▶
  ]


在我的刀片视图中,我有这段代码来循环遍历每个项目并将背景路径显示为图像

  @foreach ($similar['backdrop_path'] as $image)
            <div class="mt-8">
                <a href="#">
                    <img src=" $image " >
              </a>
           </div>

        @endforeach

问题是它导致“尝试访问类型为 null 的值的数组偏移量”错误消息。 我怎样才能达到预期的效果?谢谢。

【问题讨论】:

【参考方案1】:

你必须像下面这样使用

@foreach ($similarCollection as $image)
    <div class="mt-8">
        <a href="#">
            <img src=" $image->backdrop_path " >
        </a>
    </div>
@endforeach

【讨论】:

以上是关于使用集合循环遍历数组的主要内容,如果未能解决你的问题,请参考以下文章

jdk 5.0 新增的foreach循环(用于遍历集合数组)

iOSDay16之集合遍历和数组排序

数组的九种遍历方法

js的Dom对象集合循环遍历过程中数组长度发生变化,小白不懂,求大神指教

JS数组遍历方法集合

java怎么遍历一个枚举数组的所有集合?