1

我有一个这样的数组:

Array (
    0 => Array ( 
        'id' => 1,
        'name' => 'Hack n\' Slash',
        'slug' => 'hack-n-slash',
        'popular' => 0
    ),
    1 => Array ( 
        'id' => 2,
        'name' => 'FPP',
        'slug' => 'fpp',
        'popular' => 1
    ),  
    2 => Array ( 
        'id' => 3,
        'name' => 'RPG',
        'slug' => 'rpg',
        'popular' => 1
    )
)

我想要的是通过 key 将它分成两个数组popular,所以我会有一个类似的列表:

受欢迎的:

不受欢迎:

我尝试像这样使用 if/else:

foreach($genres as $genre) : 
    if($genre['popular'] == '1' : 
        echo $genre['name']; 
    endif; 
endforeach;

但是,当我添加另一个语句 ( if($genre['popular'] == '0')) 时,我无法使用它,因为它非常混乱。

我怎样才能做到这一点?

4

4 回答 4

1
<?php

    $pages   = array(
        array(
            "id"      => 1,
            "name"    => "Hack n' Slash",
            "slug"    => "hack-n-slash",
            "popular" => 0
        ),
        array(
            "id"      => 2,
            "name"    => "FPP",
            "slug"    => "fpp",
            "popular" => 1
        ),
        array(
            "id"      => 3,
            "name"    => "RPG",
            "slug"    => "rpg",
            "popular" => 1
        )
    );
    $results = array();
    foreach ($pages as $page) {
        $results[$page["popular"]][] = $page["name"];
    }

    print_r($results);

在这种情况下,$results[0]将包含一个不受欢迎的页面列表,$results[1]并将包含一个受欢迎的页面列表。

于 2012-08-03T08:41:20.627 回答
0

为什么不做类似的事情

$popular = array();
$notPopular = array();
foreach($genres as $genre) {
    if($genre['popular'] == '1')
        $popular[] = $genre;
    else
        $notPopular[] = $genre;
}

并在代码中使用大括号?:)

于 2012-08-03T08:45:29.533 回答
0

更通用的解决方案,使用 PHP 闭包

$pages   = array(
        array(
            "id"      => 1,
            "name"    => "Hack n' Slash",
            "slug"    => "hack-n-slash",
            "popular" => 0
        ),
        array(
            "id"      => 2,
            "name"    => "FPP",
            "slug"    => "fpp",
            "popular" => 1
        ),
        array(
            "id"      => 3,
            "name"    => "RPG",
            "slug"    => "rpg",
            "popular" => 1
        )
    );

function myFilter($arrayValues,$key,$value) {
    return array_filter($arrayValues,
                        function($entry) use ($key,$value) {
                            return $entry[$key] == $value;
                        }
            );
}

$popular = myFilter($pages,'popular',1);
var_dump($popular);
$unpopular = myFilter($pages,'popular',0);
var_dump($unpopular);
于 2012-08-03T08:53:57.213 回答
0

为您要拆分的键构建一个数组(让我们称之为键数组)。对于原始数组中的每个条目,如果它的键尚未出现在键数组中,则为其创建一个新的 Array()。然后,只需将条目推入其键数组数组即可。

function split_by_key($entries, $key) {
    $results = array();
    foreach ($entries as $entry) {
        $results[$entry[$key]][] = $entry;
    }
    return $results;
}

用于

$by_popularity = split_by_key($pages, 'popular');
$popular = $by_popularity[1];
$not_popular = $by_popularity[0];
于 2012-08-03T08:41:22.167 回答