将流派 ID 与名称匹配 - TMDB

Match genre IDs with Names - TMDB

我有以下流派 ID 数组:

$genre_ids = array(28, 12, 80);

我知道 28 表示动作,12 表示冒险,16 表示动画 我想将上面的 genre_ids 数组转换为流派名称

以下代码可以完成工作,但我不确定这是否是一个好的做法。

<?php

$genres = array(
    28 => "Action",
    12 => "Adventure",
    16 => "Animation"
);

$ids = array(28, 12, 80);

foreach ($ids as $id) {
    echo $genres[$id] . "<br>";
}

?>

由于您要遍历所有流派 ID,但并非所有流派 ID 都有流派名称,因此您会在每个没有名称的 ID 上得到 Notice: Undefined offset。这可能不是一个重大问题,您可以排除生产日志中的通知,但由于不必要(但很容易避免)通知,它会使开发期间使用日志进行调试变得非常困难。

在引用它们之前先尝试检查 key/offset,例如:

foreach ($ids as $id) {
    echo isset($genres[$id]) ? "{$genres[$id]}<br>" : '<br>';
    // Or
    echo ($genres[$id] ?? '') . '<br>';
}

我们也可以在没有任何循环和 ifs/ternary 运算符的情况下做到这一点,并且当我们有 100 种或更多类型时可能是有利的(看看是否值得的基准):

$genres = array(
    28 => "Action",
    12 => "Adventure",
    16 => "Animation",
    ...
);

$ids = array(28, 12, 80, ...);

// Turn the ids into keys so we can perform operations by keys
$keyedIds = array_flip($ids);  // [28 => 0, 12 => 1, 80 => 2, ...];
// Exclude ids that already has genre names
$unnamedIds = array_diff_key($keyedIds, $genres);  // [80 => 2, ...];
// Turn the remaining ids/keys back to values
$unnamedIds = array_flip($unnamedIds);  // [2 => 80, ...];
// Create an array similar to $genres, but for ids with no genre names, with a specified "name"
$defaultNames = array_fill_keys($unnamedIds, 'Unknown genre');  // [80 => 'Unknown genre', ...]

$genres = $genres + unnamedIds;  // [28 => 'Action', 12 => 'Adventure', 80 => 'Unknown genre', ...];
echo implode('<br>', $genres) . '<br>';  // Action<br>Adventure<br>Unknown genre...<br>