使用Laravel Collection中的函数

时间:2016-12-04 22:18:19

标签: php laravel laravel-5 laravel-5.2 laravel-5.3

我有一个带有设计的数组配置,每个设计对应一个主要标签类别,但有些设计有两个主要标签,例如口袋妖怪+权力游戏:

'b5u8ic66ywua' => array(
        'design_id'     => 'b5u8ic66ywua',
        'design_name' => 'choose dragon blanket',
        'main_tag'    => 'pokemon,game of thrones',
        'tags'        => array('pokemon','pixelart','game of thrones'),
        'article_owner' => '1426',

    ),
    'dx6nalh1bkk4' => array(
        'design_id'     => 'dx6nalh1bkk4',
        'design_name' => 'choose direwolf blanket',
        'main_tag'    => 'pokemon,game of thrones',
        'tags'        => array('pokemon','pixelart','game of thrones'),
        'article_owner' => '1426',

    ), 
    'ih91h1i77g9j' => array(
        'design_id'     => 'ih91h1i77g9j',
        'design_name'   => 'game of thrones pixelart',
        'main_tag'      => 'game of thrones',
        'tags'          => array('game of thrones','stark','jon snow','daenerys', 'danny','pixelart','game of thrones'),
        'article_owner' => '1426',

    ),

    'wolcf2m524nu' => array(
        'design_id'     => 'wolcf2m524nu',
        'design_name'   => 'starks revenge',
        'main_tag'      => 'game of thrones',
        'tags'          => array('game of thrones','stark','house stark','starks'),
        'article_owner' => '1426',

    ),

在这种情况下,我希望将包含主要标签的所有设计作为权力游戏,并使用这些设计创建一个集合。

我正在使用where函数。例如,在这种情况下,category_design_name是'权力游戏':

$family_article_designs = collect(config('artdesigns.'.$article_id))->where('main_tag',str_replace("-", " ", $category_design_name));

$family_article_designs = $family_article_designs->all();

这给我的设计只返了main_tag =权力游戏,但是没有给我带来多个main_tag的设计:

'ih91h1i77g9j' => array(
        'design_id'     => 'ih91h1i77g9j',
        'design_name'   => 'game of thrones pixelart',
        'main_tag'      => 'game of thrones',
        'tags'          => array('game of thrones','stark','jon snow','daenerys', 'danny','pixelart','game of thrones'),
        'article_owner' => '1426',

    ),

    'wolcf2m524nu' => array(
        'design_id'     => 'wolcf2m524nu',
        'design_name'   => 'starks revenge',
        'main_tag'      => 'game of thrones',
        'tags'          => array('game of thrones','stark','house stark','starks'),
        'article_owner' => '1426',

    ),

我希望得到所有的设计,其中包含“权力游戏”这个词。

编辑:

$family_article_designs = collect(config('artdesigns.'.'@'.$article_id))->filter(function ($value, $key) {
                            if(strpos($value['main_tag'], str_replace("-", " ", $category_design_name)) !== false)
                             return true;
                        });

这回复我:未定义的变量:category_design_name

1 个答案:

答案 0 :(得分:1)

您忘记使用变量名称:

$family_article_designs = collect(config('artdesigns.'.'@'.$article_id))->filter(function ($value, $key) use($category_design_name) {
    if(strpos($value['main_tag'], str_replace("-", " ", $category_design_name)) !== false)
     return true;
});