【问题标题】:How to get first title from string for the array如何从数组的字符串中获取第一个标题
【发布时间】:2019-10-29 01:20:58
【问题描述】:

我正在尝试从电影中获取所有类型并将它们自动放入选择列表中,而无需硬编码。因此,如果我在 octobercms 后端创建一部新电影并将这些类型“恐怖、神秘、惊悚”添加到选择列表中,那么我想知道如何将这些类型分开用于选择列表,或者只是将“恐怖”添加到选择列表。

我只是一直收到这些错误:

strtok() expects parameter 1 to be string, array given
preg_split() expects parameter 2 to be string, array given

到目前为止我在做什么:

 function onFilterMovies() {

 $this->prepareVars();

 }

 function prepareVars() {

 $options = post('Filter', []);

 $this['movies'] = Movie::listFrontEnd($options);


 $movies = Movie::all();
 $genres = [];

 foreach($movies as $movie) {

 $genres[] = $movie->genre;

 }

 $this['genres'] = $genres;

 }


<select class="dropdown" name="Filter[genres]"> 
    <option value="">Genres</option>
    {% for genre in genres | sort %}
    <option value="{{genre}}">{{ genre }}</option> 
    {% endfor %}
</select>

选择列表的图像:

【问题讨论】:

    标签: php arrays laravel octobercms


    【解决方案1】:

    您可以使用array_reduce 结合preg_split 来抓取所有类型,然后使用array_unique 来删除重复项:

    $genres = array_unique(array_reduce($movies, static function ($genres, $movie) {
      $movie_genres = preg_split('/\s*,\s*/', $movie->genre);
      return array_merge($genres, $movie_genres);
    }, []));
    

    然后你只需要为你的选择元素循环遍历该数组。

    演示:https://3v4l.org/I8JQP

    【讨论】:

    • 您好,感谢您的回复。现在我得到了这些错误:array_reduce() 期望参数 1 是数组,对象给定我编辑了我的第一篇文章(整个代码)。
    • @Pyramidhead85 我想这是一个 Laravel 集合。尝试将第一个参数从 $movies 更改为 $movies-&gt;toArray()?如果可行,我将使用更简洁的解决方案编辑我的帖子(Laravel 集合本身有一个 reduce 方法)。
    • 嗨,无法使用 toArray(),未定义变量:电影等...
    • @Pyramidhead85 movies 不能未定义,您在原始代码中循环它。
    【解决方案2】:

    尝试使用数组爆炸:

    $title = 'a, b, c';
    array_explode($title, ','); // ['a', 'b', 'c']
    

    https://www.php.net/manual/en/function.explode.php

    【讨论】:

      【解决方案3】:

      你也可以用 Laravel 方式使用 pluck 和 reduce

      $this['genres'] = Movie::all()->pluck('genre')->reduce(static function ($genres, $itemGenre) {
          array_merge($genres, explode(',', $itemGenre));
      }, []);
      

      【讨论】:

      • 感谢您的回复,但我得到了这个:array_merge(): Argument #1 is not an array
      猜你喜欢
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      相关资源
      最近更新 更多