如何遍历数组并计算演员所在的电影数量

时间:2014-11-04 02:18:58

标签: php arrays

我需要编写一个php脚本,它将遍历数组并显示

中的actor

按字母顺序排列的数组以及它们出现的电影数量:

$movies = array (
"horror"=>array (
  "Paranormal Activity"=> array (
      "Katie Featherston",
      "Kathryn Newton"
  ),
  "The Ring"=> array (
      "Naomi Watts",
      "Brian Cox"
  ),
  "Sleepy Hollow"=> array(
      "Johnny Depp",
      "Christina Ricci"
   )
),
"action" => array (
    "The Tourist"=> array (
        "Johnny Depp",
        "Angelina Jolie"
    ),
    "Public Enemies"=> array (
        "Johnny Depp",
        "Christian Bale"
    ),
    "The Dark Knight Rises"=> array (
        "Christian Bale",
        "Tom Hardy"
    ),
    "Salt"=> array (
        "Angelina Jolie"
    )
),
"thriller"=> array (
    "Inception"=> array(
        "Leornardio Dicaprio",
        "Tom Hardy"
    ),
    "Changeling" => array(
        "Angelina Jolie"
    ),
    "The Game"=> array(
        "Michael Douglas",
        "Sean Penn"
    )
 )
);

应该看起来像:

Angelina Jolie (3)等等......

2 个答案:

答案 0 :(得分:3)

如果我明白你想做什么,你需要重建阵列,这样做的基本方法是:

(我不确定这是最好的方法,在5分钟内完成)

$results = array();

foreach($movies as $cat => $films)
{
    foreach( $films as $film => $actors)
    {
        foreach($actors as $actor)
        {
            if(!isset($results[$actor]))
            {
                $results[$actor] = array();
            }
            $results[$actor][] = array('cat' => $cat, 'title' => $film);
        }
     }
}

ksort($results);

foreach($results as $actor => $films)
{
    $films_count = count($films);

    echo '- '.$actor.' ('.$films_count.')<br/>';
}

将返回:

- Angelina Jolie (3)
- Brian Cox (1)
- Christian Bale (2)
- Christina Ricci (1)
- Johnny Depp (3)
- Kathryn Newton (1)
- Katie Featherston (1)
- Leornardio Dicaprio (1)
- Michael Douglas (1)
- Naomi Watts (1)
- Sean Penn (1)
- Tom Hardy (2)

编辑:对不起,忘记排序,完成:)(添加了演员(电影和电影中的猫)的详细信息)

答案 1 :(得分:2)

这可以通过递归使用数组,然后使用array_count_values()

来简化
$movies = array ("horror"=>array ( "Paranormal Activity"=> array ( "Katie Featherston", "Kathryn Newton" ), "The Ring"=> array ( "Naomi Watts", "Brian Cox" ), "Sleepy Hollow"=> array( "Johnny Depp", "Christina Ricci" )),"action" => array ( "The Tourist"=> array ( "Johnny Depp", "Angelina Jolie" ), "Public Enemies"=> array ( "Johnny Depp", "Christian Bale" ), "The Dark Knight Rises"=> array ( "Christian Bale", "Tom Hardy" ), "Salt"=> array ( "Angelina Jolie" )),"thriller"=> array ( "Inception"=> array( "Leornardio Dicaprio", "Tom Hardy" ), "Changeling" => array( "Angelina Jolie" ), "The Game"=> array( "Michael Douglas", "Sean Penn" ) ));
$actors = array();
array_walk_recursive($movies, function($val) use (&$actors){
    $actors[] = $val;
});

$count = array_count_values($actors);
ksort($count);
foreach ($count as $actor_name => $appearances) {
    echo "$actor_name ($appearances) <br/>";
}

Sample Out