gpt4 book ai didi

php - 如何检查数组中是否存在给定的键或索引?

转载 作者:行者123 更新时间:2023-11-29 22:30:21 25 4
gpt4 key购买 nike

我已经从 mysql 数据库创建了一个数据数组。该数组如下所示:

// Fetch all the records:
while ($stmt->fetch()) {

$output = "<a>\n";
$output .= "<h3>{$product_name}</h3>\n";
$output .= "<span class='price'><span class='amount'>BD.{$price}</span></span>\n";
$output .= "</a>\n";
$output .= "<div class='short_desc'>\n";
$output .= "$product_des\n";
$output .= "</div>\n";

//Add output to array
$products[] = $output;
}

因为我想在 while 循环外部使用此数组值,这就是我在页面中使用此 $products[] 数组的方式。

echo $products[0];
echo $products[1];
echo $products[2];
echo $products[3];

我的问题是,如果这个 $products[] 数组有一个结果集,我会收到错误消息。

My error message is like this: An error occurred in script 'C:\wamp\www\Computer\index.php' on line 208: Undefined offset: 2

所以我尝试使用 array_key_exists() 函数来解决这个问题,就像每个 echo 一样:

if(!empty($products) && array_key_exists("$products[1]", $products)) echo $products[1]; else echo "No Product";

但我仍然会收到错误。谁能告诉我这有什么问题吗?

谢谢。

最佳答案

你可能想要这样的东西:

if( ! empty($products) ) {
$ids = array(0, 1, 2, 3, 4, 5);
foreach ( $ids as $id ) {
if ( ! empty($products[$id]) ) echo $products[$id];
}
} else {
echo "No Product";
}

关于php - 如何检查数组中是否存在给定的键或索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865296/

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