如何在switch语句中放入循环?的PHP

时间:2018-09-17 23:51:16

标签: php database loops switch-statement

$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”的表,我会将变量的值放在此表中。

编辑:

我将不得不编写许多切换用例,因此,我要写的只是表上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;

1 个答案:

答案 0 :(得分:1)

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

  $ stmtUN =“ SELECT * FROM表”;
$ pUN = $ conn-> query($ stmtUN)-> fetchAll();

foreach($ pUN为$ UN):
   echo $ UN [“ title”];

   切换($ post):

      案例$ 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”]':
        打破;

   终端开关;

endforeach;