【问题标题】:Match genre IDs with Names - TMDB将流派 ID 与名称匹配 - TMDB
【发布时间】:2020-12-27 13:36:48
【问题描述】:

我有以下流派 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>";
}

?>

【问题讨论】:

  • 由于流派是由 API 管理的,我会说这是一种有效的方式。不过,我可能会从their API 获取流派列表。

标签: php arrays foreach associative-array


【解决方案1】:

由于您循环遍历所有流派 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多