如何将关联数组传递给 PHP 中的函数参数

How to pass associative array into function argument in PHP

我可以将关联数组名称传递给 PHP 中的函数参数吗?我有以下数组,我想显示 "comedy" 下的所有电影。例如,我想要 filmsInCategory("comedy") 到 return 所有喜剧类别的电影。

$film = array(
  "comedy" => array(
    0 => "Pink Panther",
    1 => "john English",
    2 => "See no evil hear no evil"
  ),

  "action" => array (
    0 => "Die Hard",
    1 => "Expendables"
  ),

  "epic" => array (
    0 => "The Lord of the rings"
  ),

  "Romance" => array(
    0 => "Romeo and Juliet"
  )
);

//print_r($film);

$category;

function filmsInCategory($category) {
  echo $film[$category];
}

filmsInCategory("comedy");

foreach ($film as $key => $value) {
  echo $key . " = " . $value . "<br>";
  echo "Should output: " . $film["comedy"];
}

?>

怎么了

foreach ($film as $key => $value) {
    //$key here is the string "comedy" / $value here is the inner array
    filmsInCategory($key);
}

我的变量超出范围。我把它放在函数中而不是

function filmsInCategory($category) {
  $film = array(
    "comedy" => array(
      0 => "Pink Panther",
      1 => "john English",
      2 => "See no evil hear no evil"
    ),

    "action" => array (
      0 => "Die Hard",
      1 => "Expendables"
    ),

    "epic" => array (
      0 => "The Lord of the rings"
    ),

    "Romance" => array(
      0 => "Romeo and Juliet"
    )
  );
  // print_r($film);


  if ( array_key_exists($category, $film) ) {
    echo $category . " exists" . "<br>";

    foreach ($film[$category] as $key => $value) {
      echo $value . "<br>";
    }
  }
}

filmsInCategory("action");

?>