如何在switch语句中放置一个循环? PHP [关闭]

问题描述 投票:0回答:1
$stmt = "SELECT * FROM table";
$pUN  = $conn->query($stmt)->fetchAll();

$post = empty($_GET['post']) ? '' : $_GET['post'];
$paginas = empty($_GET['p']) ? 'home' : $_GET['p'];

if ($post != '' || ($post == '' && $paginas != '')) {
switch ($paginas):
    case " ":
        $titulo = " ";
        $shareTitulo = " ";

        $descricao = " ";
        $shareDescricao = " ";

        $shareImg = ' ';
        $keywords = ' ';

        $ogUrl = ' ';
        $urlCanonico = ' ';
        break;

    default:
        $titulo = '';
        $paginas = '';

endswitch;


switch ($post):

    case " ":
        $titulo = " ";
        $shareTitulo = " ";

        $descricao = " ";
        $shareDescricao = " ";

        $shareImg = ' ';
        $keywords = ' ';

        $ogUrl = ' ';
        $urlCanonico = ' ';
        break;

endswitch;

} else {
    $titulo = 'Notícia';
  }

我想在switch ($post)中放一个循环,switch ($post)上的变量值将在我的数据库中。

如何在switch ($post)中放置一个循环来从我的数据库中获取数据?我有一个名为“SwitchCase”的表,我将把变量的值放在这个表中。

编辑:

我必须编写这么多的switch-case,所以我想简单地在我的表上的case中写入变量的值,而我希望这个循环返回数据。

例:

$stmtUN = "SELECT * FROM table";
$pUN    = $conn->query($stmtUN)->fetchAll();

switch ($post):

    foreach ($pUN as $UN): 

        case 'echo $UN["title"]':
            $titulo = 'echo $UN["title"]':
            $shareTitulo = 'echo $UN["title"]':

            $descricao = 'echo $UN["text"]':
            $shareDescricao = 'echo $UN["text"]':

            $shareImg = 'echo $UN["img"]':
            $keywords = 'echo $UN["keywords"]':

            $ogUrl = 'echo $UN["cnc"]':
            $urlCanonico = 'echo $UN["cnc"]':
        break;

    endforeach;

endswitch;
php database loops switch-statement
1个回答
1
投票

您已将开关块放在错误的位置。请参阅更正的代码。还有理由将'echo'字符串作为变量的一部分吗?

$stmtUN = "SELECT * FROM table";
$pUN    = $conn->query($stmtUN)->fetchAll();

foreach ($pUN as $UN): 
   echo $UN["title"];

   switch ($post):

      case $UN["title"]:

        $titulo = 'echo $UN["title"]':
        $shareTitulo = 'echo $UN["title"]':

        $descricao = 'echo $UN["title"]':
        $shareDescricao = 'echo $UN["title"]':

        $shareImg = 'echo $UN["title"]':
        $keywords = 'echo $UN["title"]':

        $ogUrl = 'echo $UN["title"]':
        $urlCanonico = 'echo $UN["title"]':
        break;

   endswitch;

endforeach;
© www.soinside.com 2019 - 2024. All rights reserved.