嗨,我正在尝试显示 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/>";
}
}