[英]Php inside foreach loop if $i == 1 echo “ok”, else echo “ok” JUST one time and continue
[英]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.