三元运算符 - 如何在 (expr1) 上添加 (expr4)? (表达式 2) : (表达式 3)

Ternary Operator - How to add a (expr4) on (expr1) ? (expr2) : (expr3)

我有两个查询字符串:?page 和 ?p。我在这些查询字符串上使用 slug 作为 link,例如: ?p/?page=slug-link 。并且这些 link 仅当它在下面的三元运算符上指定了 entry_type 时才可访问。我当时只使用两种类型的 entry_type 并且它工作得很好,但现在我需要添加 +1 类型的 entry_type.

我正在尝试使用以下代码来完成:

<?php
$Q = !empty($_GET['post']);
$slug =  'home';

if ($Q) {
    $slug = $_GET['post'];
} elseif (!empty($_GET['p'])) {
    $slug = $_GET['p'];
}
try {
    $stmt = $conn->prepare('SELECT `id`, `title`, `description`, `img`, `alt`, `keywords`, `art`, `slug_url`, `slug_link`, `entry_type` FROM table_tudo WHERE `slug_link` = :slug_link AND `entry_type` = :entry_type');
    $stmt->execute([
        ':entry_type' => ($Q) ? ('entry1') : (('entry2') ? ('entry2') : ('entry3')), 
        ':slug_link' => $slug
    ]);
    if (!$NF = $stmt->fetch(\PDO::FETCH_ASSOC)) {       
        throw new \InvalidArgumentException('Title ' . htmlentities($title, \ENT_QUOTES, 'UTF-8', false) . ' not found in database');
    }   
    $id              = $NF['id'];
    $title           = $shareTitle       = $NF['title'];
    $description     = $shareDescription = $NF['description'];
    $shareImg        = $NF['img'];
    $alt             = $NF['alt'];
    $keywords        = $NF['keywords'];
    $art             = $NF['art'];
    $ogUrl           = $urlCanonical     = $NF['slug_url'];
    $slug            = $NF['slug_link'];
    $entry_type      = $NF['entry_type'];

} catch (\InvalidArgumentException $e) {
    header('Location: index.php?p=home'); 
    exit;
} catch (\Exception $e) {
  header('Location: error.php?e=Oops an error occurred');
  throw $e;
}
function sanitize($data, $filter = \FILTER_SANITIZE_STRING) {
    if ($data = filter_var(trim($data), $filter)) {
        $data = preg_replace('/http(s)?:\/\//', '', $data);
    }   
    return $data;
}
$loadPage = null;
if ($sanitizedName = sanitize($Q ? $title : $slug)) {
    $loadPageSuffix = ($Q ? '/myDirectory/' : '/page_');
    $loadPage =  __DIR__ . $loadPageSuffix . $name . '.php';
}
if (null === $loadPage || !is_file($loadPage)) {
    header('HTTP/1.1 404 Not Found'); 
    exit;
}

index.php:

<?php
require_once 'load.php';
?>
...
...
<body>
  <?php require_once $loadPage; ?>
...
...

我也用这段代码来拥有一些全局变量。

':entry_type' => ($Q) ? ('entry1') : (('entry2') ? ('entry2') : ('entry3')), 的旧版本是:':entry_type' => $Q ? 'entry1' : 'entry2', 旧版本正在运行。我很难尝试更改此三元运算符。

之前,我有两个 entry_typesentry1entry2。但是我需要在查询字符串 ?post 中添加一个 entry3。并且 entry3 可以在目录 /myDirectory/.

上访问

有人可以帮我吗?

我同意 Frederico 的观点,如果它在您将来查看时不可读,您将不知道发生了什么。我也建议 switch case 但为什么不删除三元并使用

if ( $Q ) {
    $entry='entry1'; 
} elseif ( $Q2 ) {
    $entry='entry2';
} else {
    $entry='entry3';
}

然后使用':entry_type' => $entry

确实'entry2'总是return正确(拍脑袋)