按键内部拆分数组

时间:2012-08-03 08:33:16

标签: php

我有一个这样的数组:

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
    )
)

我想要的是按键popular将其拆分为两个数组,所以我会有一个列表:

流行:

  • 一个
  • 2

非流行:

  • 一个
  • 2

我尝试使用if / else这样:

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

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

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分: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]将包含受欢迎的网页列表。

答案 1 :(得分: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];

答案 2 :(得分:0)

为什么不做像

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

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

答案 3 :(得分: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);