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

问题描述 投票:0回答:1

我可以在PHP的函数参数中传递关联数组名称吗?我有以下数组,我想在“喜剧”下显示所有电影。例如,我希望filmsInCategory("comedy")返回喜剧类别中的所有电影。

$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"];
}

?>

php multidimensional-array associative-array
1个回答
0
投票

怎么了

foreach ($film as $key => $value) {
    //$key here is the string "comedy" / $value here is the inner array
    filmsInCategory($key);
}
© www.soinside.com 2019 - 2024. All rights reserved.