将流派 ID 与名称匹配 - TMDB

问题描述

我有以下流派 ID 数组:

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

我知道 28 表示动作,12 表示冒险,16 表示动画 我想把上面的流派_id数组变成流派名称

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

<?PHP

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

$ids = array(28,80);

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

?>

解决方法

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

在引用它们之前先尝试检查键/偏移量,例如:

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

我们也可以在没有任何循环和 ifs/三元运算符的情况下执行此操作,并且当我们有 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>