如何获取PHP中的键名?

How to get the key name in PHP?

我最近有一个项目,我必须创建一个必须关联的 third-dimensional 数组。

所以我定义了一个 third-dimensional 数组,如下所示:

$movies = array(
    "Action" => array(
        array(
            "Title" => "Nobody",
            "Year Released" => "2021"
        ),
        array(
            "Title" => "Monster Hunter",
            "Year Released" => "2020"
        ),
        array(
            "Title" => "Tenet",
            "Year Released" => "2020"
        ),
        array(
            "Title" => "The Hitman's Bodyguard",
            "Year Released" => "2017"
        ),
        array(
            "Title" => "Wrath of Man",
            "Year Released" => "2021"
        )
    ),

    "Comedy" => array(
        array(
            "Title" => "The Hangover",
            "Year Released" => "2009"
        ),
        array(
            "Title" => "Minions",
            "Year Released" => "2015"
        ),
        array(
            "Title" => "Deadpool",
            "Year Released" => "2016"
        ),
        array(
            "Title" => "Scary Movie",
            "Year Released" => "2000"
        ),
        array(
            "Title" => "Blockers",
            "Year Released" => "2018"
        )
    )
);

我试图显示电影的类型,以及它们的标题和发行年份。但是,每当我尝试获取流派时,我都会得到 Array。这是我使用的代码:

foreach ($movies as $genres) {
    echo "$genres <br>";

    while (list ($index, $array) = each ($genres)) {
        echo "Movie number: $index <br>";
    
        while (list ($k, $v) = each ($array)) {
            echo "$k - $v <br>";
        }
        echo "<br>";
    }
    echo "<br>";
}

部分结果(在实际页面上,每行被分成四行,只是这个网站把结果弄乱了。):

数组 影片编号:0 标题 - 没有人 发行年份 - 2021

电影数量:1 称号 - 怪物猎人 发行年份 - 2020

电影数量:2 标题 - 信条 发行年份 - 2020

影片数:3 标题 - 杀手的保镖 发行年份 - 2017

影片数:4 作品名 - 人类之怒 发行年份 - 2021

如何获得流派的名称?

您可以在 for each 循环中使用关键语法

foreach ($movies as $genreName => $genres) {
    echo "$genreName <br>";

    while (list ($index, $array) = each ($genres)) {
        echo "Movie number: $index <br>";
    
        while (list ($k, $v) = each ($array)) {
            echo "$k - $v <br>";
        }
        echo "<br>";
    }
    echo "<br>";
}

阅读foreach manual

foreach

有两种语法
foreach (iterable_expression as $value)
    statement

foreach (iterable_expression as $key => $value)
    statement

来自 php.net、

第一种形式遍历iterable_expression给出的iterable。在每次迭代中,当前元素的值被分配给 $value.

第二种形式会在每次迭代时将当前元素的键另外分配给 $key 变量。

我会像这样重写你的代码

printEach($movies);

function printEach($array) {
  echo "<br><br>";
  foreach ($array as $key => $value) {
    echo $key;
    if (is_array($value)) {
       printEach($value); // Recursive
    } else {
      echo " - ".$value."<br><br>";
    }
  }
}