gpt4 book ai didi

php - 如何只为 php foreach 循环结果回显一条消息并在没有结果时隐藏该消息?

转载 作者:行者123 更新时间:2023-11-29 14:05:56 26 4
gpt4 key购买 nike

您好,我正在尝试为 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
}

关于php - 如何只为 php foreach 循环结果回显一条消息并在没有结果时隐藏该消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com