三元运算符-如何在(expr1)上添加(expr4)? (expr2):(expr3)

时间:2018-11-14 16:57:13

标签: php if-statement server-side ternary-operator

我有两个查询字符串:?page和?p。我正在使用slug作为这些查询字符串的链接,例如:?p /?page = slug-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。但是我需要在查询字符串entry3中添加?postentry3可以在目录/myDirectory/上访问。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我同意弗雷德里克(Frederico)的看法,如果将来阅读时不可读,您将不知道发生了什么。我也建议切换大小写,但为什么不删除三元并使用

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

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

确实要输入'entry2'总是返回true(拍头后脑)