首页 > 解决方案 > 在php中显示数组列表中的所有记录

问题描述

我有一个运行良好的脚本,它一次显示 2 条记录。我想实际显示数组数据中的所有记录。我对jquery不是很熟悉,脚本使用jquery。

基本上它是这样工作的……用户在一个页面上提交一个问题,然后提交的问题显示在第二个页面上。你可以在这里试试:

提交问题:http ://www.webcastviewer.com/post/submit.php

列出问题:http ://www.webcastviewer.com/post/list.php

在“列表”页面上:目前它列出了两个最近的问题。最近的问题是顶部的蓝色/较大字体。我想要的改变是我希望它列出所有问题,最近的问题在顶部(就像现在一样)。目前较旧的问题在两次输入后消失。我希望它显示所有提交。

App.js (jquery 代码) http://www.webcastviewer.com/post/js/app.js

用于显示 2 条记录的页面代码。

    <?php
//read questions
$question_file_path = 'server/question.list';
if(!file_exists($question_file_path)){    
    $questions = array();
}
else {
    $questions = json_decode(file_get_contents($question_file_path), true);
}

?>
<body>
    <div class="p-3" id="page_list">
        <?php
        if(count($questions) > 0){
            ?>
            <div class="questions-list">
            <?php
        }
        else{
            ?>
            <div class="questions-list questions--empty">
            <?php
        }
        ?>
            <div class="alert alert-primary questions-alert">
                <h1 id="question_new"><?php echo isset($questions[0]) ? $questions[0]: '&nbsp;'  ?></h1>
            </div>
            <div class="alert alert-info questions-alert">
                <h4 id="question_old"><?php echo isset($questions[1]) ? $questions[1] : '&nbsp;' ?></h4>
            </div>
            <div class="alert alert-danger questions-alert-empty">
                <h1 id="question_new text-danger">There isn't question.</h1>
            </div>
        </div>
    </div>

标签: php

解决方案


请看看你是怎么做到的。

我改进了部分代码并对它们进行了评论。

注意:尝试改进 PHP 与 HTML 的混合并避免使用它。

<div class="p-3" id="page_list">
    //Added ternary operator instead of typical if else.
    <div class="<?= count($questions) > 0 ? 'questions-list' : 'questions--empty'  ?>">
    <?php 
    //checking if has records else show message
        if(count($questions) > 0){
    ?>
        <?php foreach($questions as $question) ?>
            <div class="alert alert-primary questions-alert">
                <h1 id="question_new"><?php echo isset($question) ? $question: '&nbsp;'  ?></h1>
            </div>
        <?php }

    }else{ ?>

        <div class="alert alert-danger questions-alert-empty">
            <h1 id="question_new text-danger">There isn't question.</h1>
        </div>

    <?php } ?>
    </div>
</div>

推荐阅读