簡體   English   中英

如何只為php foreach循環結果回顯一條消息,如果沒有結果則隱藏該消息?

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

嗨,我正在嘗試為php foreach循環的結果顯示一條常見消息。 該消息必須在結果之前顯示,如果沒有結果,則不應顯示該消息。

<!-- 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' ';
    } 
}

問題在於,多個值不會在循環外部顯示,並且結果不會在循環之前顯示。 我該如何解決?

不要立即回顯您的輸出,而是將其存儲在字符串變量中,然后在標簽之后輸出

<?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