简体   繁体   English

如何只为php foreach循环结果回显一条消息,如果没有结果则隐藏该消息?

[英]How to echo just one message for a php foreach loop result and hide the message if there are no results?

Hi I am trying to display a common message for the results of a php foreach loop. 嗨,我正在尝试为php foreach循环的结果显示一条常见消息。 The message has to be displayed before the results, and should not be displayed if there are no results. 该消息必须在结果之前显示,如果没有结果,则不应显示该消息。

<!-- An array coming from the previous page -->
$string = explode(PHP_EOL, trim($_SESSION['grid']));

<!-- HIDE THIS MESSAGE IF THERE ARE NO RESULTS --> 
<label>These barcodes don't exist:</label>   

foreach ($string as $value) {
    <!-- SQL QUERY -->
    $query1 = "select addl_item_code_barcode from items where 
    addl_item_code_barcode = '$value';";
    $result = pg_query($db, $query1);

    <!-- IF THE VALUES IN THE ARRAY DON'T EXIST IN THE DATABASE THEN IT IS TO 
    BE DISPLAYED -->
    if (pg_num_rows($result) == 0) {
        echo $value; echo' ';
    } 
}

The problem is that multiple values won't be displayed outside the loop, and the results won't be displayed before the loop. 问题在于,多个值不会在循环外部显示,并且结果不会在循环之前显示。 How do I solve this? 我该如何解决?

Don't echo your output immediately, but store it in a string variable and then output it after your label 不要立即回显您的输出,而是将其存储在字符串变量中,然后在标签之后输出

<?php
// An array coming from the previous page
$string = explode(PHP_EOL, trim($_SESSION['grid']));
$values = "";

foreach ($string as $value) {
    <!-- SQL QUERY -->
    $query1 = "
        SELECT addl_item_code_barcode 
          FROM items 
         WHERE addl_item_code_barcode = '$value'
             ;
    ";
    $result = pg_query($db, $query1);

    // IF THE VALUES IN THE ARRAY DON'T EXIST IN THE DATABASE THEN IT IS TO BE DISPLAYED
    if (pg_num_rows($result) == 0) {
        $values .= "{$value} ";
    } 
}

if (strlen($values) === 0) {
    // HIDE THIS MESSAGE IF THERE ARE NO RESULTS
    ?><label>These barcodes don't exist:</label><?php
}
$nonexistent = array();
foreach ($string as $value) {

$query1 = "select addl_item_code_barcode from items where 
addl_item_code_barcode = '$value';";
$result = pg_query($db, $query1);


if (pg_num_rows($result) == 0) {
array_push($nonexistent,$value);
        } 
}
if(count($nonexistent)>0){
    echo "<label>These barcodes don't exist:</label> <br/>";
    foreach($nonexistent as $element){
        echo $element . "<br/>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM